使用c++的for循环和字符串类实现字符串逆序输出。
时间: 2024-11-20 16:37:28 浏览: 66
在C++中,你可以使用`std::string`类提供的成员函数以及`for`循环来实现字符串的逆序输出。以下是一个例子:
```cpp
#include <iostream>
#include <string>
// 定义一个函数,接受一个字符串作为参数并返回其逆序版本
std::string reverseString(const std::string &s) {
std::string reversed = "";
for (int i = s.length() - 1; i >= 0; --i) {
reversed += s[i]; // 从字符串末尾开始添加字符到新字符串
}
return reversed;
}
int main() {
std::string input = "Hello, World!";
std::cout << "Original string: " << input << "\n";
std::cout << "Reversed string: " << reverseString(input) << "\n"; // 输出 "!dlroW ,olleH"
return 0;
}
```
在这个示例中,我们首先创建了一个空字符串`reversed`,然后遍历输入字符串`s`的每个字符,从后往前添加到`reversed`,最终得到逆序的字符串。
相关问题
c++实现字符串逆序输出
可以使用C++的string类和reverse函数实现字符串逆序输出,具体代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello World!";
reverse(str.begin(), str.end()); // 使用reverse函数逆序字符串
cout << str << endl;
return 0;
}
```
输出结果为:`!dlroW olleH`。
C++逆序输出字符串
以下是两种C++逆序输出字符串的方法:
1.使用for循环逆序输出字符串
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
for (int i = str.length() - 1; i >= 0; i--) {
cout << str[i];
}
return 0;
}
// 输出:dlrow olleh
```
2.使用reverse函数逆序输出字符串
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello world";
reverse(str.begin(), str.end());
cout << str;
return 0;
}
// 输出:dlrow olleh
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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://img-home.csdnimg.cn/images/20241231044833.png)