简答题C语言如何将字符串反转
时间: 2024-02-22 07:58:12 浏览: 30
C 语言中,可以通过指针来实现字符串反转。具体实现步骤如下:
1. 定义一个指向字符串首元素的指针,以及一个指向字符串尾元素的指针;
2. 通过循环交换首尾指针所指向的元素,直到首指针不小于尾指针;
3. 反转完成后,可以输出反转后的字符串。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
void reverse(char *str) {
// 定义指向字符串首尾的指针
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("原字符串:%s\n", str);
reverse(str);
printf("反转后的字符串:%s\n", str);
return 0;
}
```
输出结果为:
```
原字符串:hello world
反转后的字符串:dlrow olleh
```