String Reverse in C

Level 5234 keystrokes

Defines a function that reverses a string in place: it counts the characters up to '\0', then swaps characters from both ends toward the middle. Reversing "Hello" prints olleH.

C code

// Receives a pointer to the string and changes it directly
1void reverse(char *str) {
// The length counter starts at 0
2 int len = 0;
// Counts characters up to the terminating '\0'; for "Hello", len becomes 5
3 while (str[len] != '\0') len++;
// Swaps pairs from both ends toward the middle; len / 2 = 2 swaps, the middle 'l' stays
4 for (int i = 0; i < len / 2; i++) {
// Saves the character at the front position i
5 char temp = str[i];
// Copies the matching character from the back (index len - 1 - i) to the front
6 str[i] = str[len - 1 - i];
// Puts the saved front character at the back
7 str[len - 1 - i] = temp;
8 }
9}
10
// An array (not a pointer to a literal), so its characters may be modified
11char s[] = "Hello";
// Reverses s in place; the array name passes the address of its first element
12reverse(s);
// Prints olleH
13printf("%s\n", s);

Output

olleH
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 10
  • =× 7
  • [× 6
  • ]× 6
  • (× 5
  • )× 5
  • -× 4
  • "× 4
  • +× 4
  • '× 2

More C examples at level 5

← C typing practice