C++引用练习。求任意字符串的反串。
时间: 2023-08-14 11:02:10 浏览: 61
可以使用 C++ 引用来交换字符串中的字符,从而实现字符串的反转。以下是示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
void reverse_string(string& str) {
int len = str.length();
for (int i = 0; i < len / 2; i++) {
char& c1 = str[i];
char& c2 = str[len - i - 1];
char temp = c1;
c1 = c2;
c2 = temp;
}
}
int main() {
string s = "hello world";
reverse_string(s);
cout << s << endl; // 输出 "dlrow olleh"
return 0;
}
```
在 `reverse_string` 函数中,我们使用了 C++ 引用来交换字符串中对应位置的字符。这样可以直接修改原字符串,避免了使用中间变量的复杂度。
相关问题
c++求任意字符串的反串
可以使用C++的字符串反转函数`reverse()`,示例代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
cout << "请输入一个字符串:";
getline(cin, str); // 获取输入的字符串,包括空格
reverse(str.begin(), str.end()); // 反转字符串
cout << "反转后的字符串为:" << str << endl;
return 0;
}
```
其中,`reverse()`函数的参数是字符串的起始地址和结束地址,通过`begin()`和`end()`获取。
C++输出任意变量为字符串的接口
在C++中,可以使用`std::to_string()`函数将各种数据类型转换为字符串,例如:
```cpp
int num = 123;
std::string str_num = std::to_string(num);
std::cout << str_num << std::endl;
```
此外,对于自定义类型,需要重载`<<`运算符来实现输出为字符串,例如:
```cpp
class Person {
public:
std::string name;
int age;
friend std::ostream& operator<<(std::ostream& os, const Person& p) {
os << "Name: " << p.name << ", Age: " << p.age;
return os;
}
};
Person p {"Tom", 20};
std::cout << p << std::endl; // 输出:Name: Tom, Age: 20
```