输入一个字符串,对该字符串进行逆序,输出逆序后的字符串。 输入格式: 输入在一行中给出一个不超过80个字符长度的、以回车结束的非空字符串。 输出格式: 在一行中输出逆序后的字符串。
时间: 2024-06-13 22:09:09 浏览: 29
可以使用C语言中的字符数组和指针来实现字符串的逆序输出。具体实现方法如下:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[81]; // 定义字符数组,用于存储输入的字符串
char *p; // 定义指针,用于指向字符数组中的字符
fgets(str, 81, stdin); // 从标准输入中读取字符串,存储到字符数组中
p = str + strlen(str) - 1; // 指针指向字符数组中最后一个字符
while (p >= str) // 从字符串末尾开始遍历
{
printf("%c", *p); // 输出当前字符
p--; // 指针向前移动一位
}
return 0;
}
```
在上面的代码中,我们首先定义了一个字符数组`str`,用于存储输入的字符串。然后使用`fgets`函数从标准输入中读取字符串,存储到字符数组中。接着定义了一个指针`p`,用于指向字符数组中的字符。指针`p`初始化为字符数组中最后一个字符的地址。然后使用`while`循环从字符串末尾开始遍历,每次输出当前字符,然后将指针向前移动一位,直到遍历完整个字符串。
相关问题
输入一个字符串,对该字符串进行逆序,输出逆序后的字符串C语言
以下是一个简单的C语言程序,实现输入字符串并输出逆序后的字符串:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, len;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
printf("逆序后的字符串为:");
for(i = len - 1; i >= 0; i--)
{
printf("%c", str[i]);
}
return 0;
}
```
运行程序后,会提示你输入一个字符串,输入后程序会将字符串逆序输出。
输入一个字符串,对该字符串进行逆序,输出逆序后的字符串。
好的,以下是 Python 代码实现:
```python
s = input("请输入一个字符串:")
reverse_s = s[::-1]
print("逆序后的字符串为:", reverse_s)
```
或者使用 `reversed()` 函数和 `join()` 方法:
```python
s = input("请输入一个字符串:")
reverse_s = ''.join(reversed(s))
print("逆序后的字符串为:", reverse_s)
```
无论哪种方法,输入字符串后,程序都会输出逆序后的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)