c++ string类倒序输出字符串
时间: 2023-07-19 07:28:11 浏览: 205
可以使用C++ STL中的reverse函数来倒序输出字符串。例如:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str = "hello world";
reverse(str.begin(), str.end());
cout << str << endl;
return 0;
}
```
输出结果为: "dlrow olleh"。
相关问题
c++倒序输出字符串
要倒序输出字符串,你可以使用循环或递归的方式来实现。下面是一个使用循环的示例代码:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
int length = strlen(str);
// 交换字符串首尾字符位置
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
reverseString(str);
printf("倒序输出为:%s\n", str);
return 0;
}
```
以上代码会先读取用户输入的字符串,然后调用 `reverseString` 函数对字符串进行倒序操作,最后输出倒序后的结果。
c++字符串倒序输出
可以使用C++标准库中的`reverse`函数来实现字符串倒序输出。具体代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s = "hello world";
std::reverse(s.begin(), s.end());
std::cout << s << std::endl; // 输出 "dlrow olleh"
return 0;
}
```
上面的代码中,`std::reverse`函数接收两个迭代器参数,表示要反转的区间。在本例中,我们传递了整个字符串`s`的迭代器范围,即`s.begin()`和`s.end()`,这样就可以将整个字符串倒序输出了。