请用c语言编写一段程序,要求应用指针实现字符串的倒置。
时间: 2023-11-27 13:54:19 浏览: 110
以下是用指针实现字符串倒置的C语言程序:
```c
#include <stdio.h>
#include <string.h>
void reverse(char* str)
{
int len = strlen(str);
char* p = str;
char* q = str + len - 1;
while(p < q)
{
char temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}
}
int main()
{
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
reverse(str);
printf("倒置后的字符串为:%s\n", str);
return 0;
}
```
在该程序中,我们首先使用`strlen()`函数获取字符串的长度,然后定义两个指针`p`和`q`,分别指向字符串的首尾。接着,我们使用`while`循环将指针`p`和`q`所指向的字符交换位置。最后,我们在`main()`函数中调用`reverse()`函数,并输出倒置后的字符串。
相关问题
请用c语言编写一段程序,要求如下:应用指针实现字符串的倒置。
以下是使用指针实现字符串倒置的C语言程序:
```c
#include <stdio.h>
#include <string.h>
void reverse_string(char *str);
int main()
{
char str[100];
printf("请输入一个字符串: ");
fgets(str, sizeof(str), stdin);
// 去掉最后的换行符
str[strcspn(str, "\n")] = '\0';
reverse_string(str);
printf("倒置后的字符串为: %s\n", str);
return 0;
}
// 使用指针实现字符串倒置
void reverse_string(char *str)
{
char *start = str;
char *end = str + strlen(str) - 1;
while (start < end)
{
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
```
程序中,我们先通过 `fgets()` 函数从标准输入读取一个字符串,然后使用 `strcspn()` 函数去掉最后的换行符。接着调用 `reverse_string()` 函数,实现倒置字符串。在该函数中,我们使用两个指针 `start` 和 `end` 分别指向字符串的首尾,通过交换它们所指向的字符实现字符串的倒置。最后将倒置后的字符串打印出来。
用c语言编写一段程序,要求:利用指针实现由键盘任意输入一串字符,将此字符串倒置输出。
以下是用指针实现字符串倒置的C语言程序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char *p1, *p2;
int len;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
p1 = str;
p2 = str + len - 1;
while (p1 < p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
p1++;
p2--;
}
printf("倒置后的字符串为:%s\n", str);
return 0;
}
```
该程序首先读入一个字符串,然后使用指针 p1 和 p2 分别指向该字符串的首尾字符。接着,使用一个循环,将 p1 和 p2 所指向的字符逐个交换,直到 p1 >= p2 为止。最后输出倒置后的字符串。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)