用指针变量实现字符串逆转
时间: 2023-08-15 09:25:44 浏览: 93
可以使用指针变量实现字符串逆转的方法有很多种,其中一种比较常见的方法如下所示:
```c
#include <stdio.h>
#include <string.h>
void reverse_string(char* str)
{
int len = strlen(str);
char* start = str;
char* end = str + len - 1;
char tmp;
while(start < end)
{
tmp = *start;
*start = *end;
*end = tmp;
start++;
end--;
}
}
int main()
{
char str[] = "hello, world!";
printf("Before reverse: %s\n", str);
reverse_string(str);
printf("After reverse: %s\n", str);
return 0;
}
```
在上述代码中,我们定义了一个 `reverse_string` 函数,该函数的参数为一个字符串的指针变量。函数中首先计算出字符串的长度,然后定义两个指针变量 `start` 和 `end`,分别指向字符串的起始位置和结尾位置。接着,我们使用一个循环来交换 `start` 和 `end` 指针所指向的字符,直到 `start` 指针超过 `end` 指针。最后,我们在主函数中调用 `reverse_string` 函数,并输出逆转后的字符串。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![dsp](https://img-home.csdnimg.cn/images/20250102104920.png)