可以通過以下方法實現字符串反轉:
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int len = strlen(str);
char reversed[len+1];
int i, j = 0;
for (i = len - 1; i >= 0; i--) {
reversed[j++] = str[i];
}
reversed[j] = '\0';
printf("Reversed string: %s\n", reversed);
}
int main() {
char str[] = "Hello World";
reverseString(str);
return 0;
}
輸出結果為:Reversed string: dlroW olleH
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int len = strlen(str);
int i, j = len - 1;
for (i = 0; i < j; i++, j--) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
printf("Reversed string: %s\n", str);
}
int main() {
char str[] = "Hello World";
reverseString(str);
return 0;
}
輸出結果為:Reversed string: dlroW olleH