Reverse String in C: Simple Guide
We can use a loop to reverse the order of the string. First, calculate the length of the string, then create a new character array with the same length as the original string. Next, use a loop to iterate through the original string from back to front, assigning each character to the new character array. Finally, output the new character array.
Here is an example code:
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int len = strlen(str);
char reverse[len + 1]; // 创建新的字符数组
int i, j;
// 逆序赋值给新的字符数组
for (i = len - 1, j = 0; i >= 0; i--, j++) {
reverse[j] = str[i];
}
reverse[len] = '\0'; // 添加字符串结束符
printf("逆序字符串: %s\n", reverse);
}
int main() {
char str[] = "Hello, World!";
printf("原字符串: %s\n", str);
reverseString(str);
return 0;
}
Output result:
原字符串: Hello, World!
逆序字符串: !dlroW ,olleH