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 directly1void reverse(char *str) { // The length counter starts at 02 int len = 0; // Counts characters up to the terminating '\0'; for "Hello", len becomes 53 while (str[len] != '\0') len++; // Swaps pairs from both ends toward the middle; len / 2 = 2 swaps, the middle 'l' stays4 for (int i = 0; i < len / 2; i++) { // Saves the character at the front position i5 char temp = str[i]; // Copies the matching character from the back (index len - 1 - i) to the front6 str[i] = str[len - 1 - i]; // Puts the saved front character at the back7 str[len - 1 - i] = temp;8 }9}10 // An array (not a pointer to a literal), so its characters may be modified11char s[] = "Hello";// Reverses s in place; the array name passes the address of its first element12reverse(s);// Prints olleH13printf("%s\n", s);Output
olleH
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