c语言字符串反转函数
时间: 2024-01-21 09:02:19 浏览: 129
C语言中可以使用以下两种方法来实现字符串反转:
方法一:使用指针进行反转
```c
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int length = strlen(str);
char* start = str;
char* end = str + length - 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);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
方法二:使用递归进行反转
```c
#include <stdio.h>
#include <string.h>
void reverseString(char* str, int start, int end) {
if (start >= end) {
return;
}
char temp = str[start];
str[start] = str[end];
str[end] = temp;
reverseString(str, start + 1, end - 1);
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverseString(str, 0, strlen(str) - 1);
printf("Reversed string: %s\n", str);
return 0;
}
```
阅读全文