字符串逆序输出c++
时间: 2023-11-30 07:37:51 浏览: 87
可以使用一个循环将字符串倒序输出,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}
return 0;
}
```
输入示例:
```
请输入一个字符串:hello world
```
输出示例:
```
dlrow olleh
```
相关问题
用栈将字符串逆序输出c++
可以通过栈的先进后出的特性,将字符串逆序输出。具体实现步骤如下:
1. 遍历字符串,将每个字符依次入栈;
2. 依次出栈每个字符,即可实现字符串逆序输出。
以下是 C++ 代码示例:
```cpp
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string str;
stack<char> stk;
cout << "请输入字符串:";
getline(cin, str); // 获取包含空格的字符串
// 将字符串中的每个字符入栈
for (int i = 0; i < str.length(); i++) {
stk.push(str[i]);
}
// 依次出栈每个字符,即可实现字符串逆序输出
cout << "逆序输出的字符串为:";
while (!stk.empty()) {
cout << stk.top();
stk.pop();
}
cout << endl;
return 0;
}
```
输入示例:
```
请输入字符串:hello world
```
输出示例:
```
逆序输出的字符串为:dlrow olleh
```
c++字符串逆序输出string
可以使用C++的标准库函数`reverse()`和迭代器来实现字符串逆序输出。具体代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "hello world";
reverse(str.begin(), str.end()); // 使用reverse()函数逆序输出
cout << str << endl;
return 0;
}
```
输出结果为:
```
dlrow olleh
```
其中,`str.begin()`和`str.end()`分别表示字符串的起始位置和结束位置,`reverse()`函数将它们之间的字符逆序输出。