1、使用两个指针进行交换
#include <stdio.h>
#include <string.h>
void reverse_string(char *str) {
if (str == NULL)
return;
char *start = str;
char *end = str + strlen(str) - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
2、递归方法
#include <stdio.h>
#include <string.h>
void reverse_string_recursive(char *str, char *left, char *right) {
if (left >= right)
return;
char temp = *left;
*left = *right;
*right = temp;
reverse_string_recursive(str, ++left, --right);
}
void reverse_string(char *str) {
if (str == NULL)
return;
reverse_string_recursive(str, str, str + strlen(str) - 1);
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
3、使用指针和循环遍历
#include <stdio.h>
#include <string.h>
void reverse_string(char *str) {
if (str == NULL)
return;
char *end = str + strlen(str) - 1;
char temp;
while (str < end) {
temp = *str;
*str++ = *end;
*end-- = temp;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
4、使用 XOR 运算进行交换
#include <stdio.h>
#include <string.h>
void reverse_string(char *str) {
if (str == NULL)
return;
char *start = str;
char *end = str + strlen(str) - 1;
while (start < end) {
*start ^= *end;
*end ^= *start;
*start ^= *end;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
5、利用临时数组
#include <stdio.h>
#include <string.h>
void reverse_string(char *str) {
if (str == NULL)
return;
int len = strlen(str);
char temp[len];
for (int i = 0; i < len; i++) {
temp[i] = str[len - 1 - i];
}
for (int i = 0; i < len; i++) {
str[i] = temp[i];
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}