c++ string
时间: 2023-09-23 10:10:03 浏览: 54
引用:在C++中,可以使用string类来表示字符串。可以通过索引或at()函数来访问string字符串的元素。例如,字符串str中的第三个字符可以使用str或str.at(2)来获取。
引用:如果需要将数值转换为字符串,在C++中可以使用stringstream类来实现。首先创建一个stringstream对象,然后使用<<操作符将数值插入对象中。最后可以使用>>操作符或str()函数将stringstream对象转换为字符串。下面是一个示例代码:
```c++
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
double a = 123.32;
string res;
stringstream ss;
ss << a;
ss >> res; // 或者 res = ss.str();
cout << res;
return 0;
}
```
这段代码将数值a转换为字符串,并将其输出。
对于string类型的字符串,可以使用比较操作符来比较字符串的大小。与C语言中的字符串比较函数不同,C++中的string类可以直接使用>、<、==、>=等数学符号进行比较。例如,可以使用==操作符来判断两个字符串是否相等,或者使用>操作符来比较两个字符串的大小。下面是一个示例代码:
```c++
#include <string>
#include <iostream>
using namespace std;
int main() {
string a;
a = "hello";
if (a == "world")
cout << "yes" << endl;
else if (a > "world") {
cout << "You win." << endl;
} else
cout << "You failed." << endl;
a = " world";
cout << a << endl;
}
```
这段代码首先给字符串a赋值为"hello",然后使用==操作符判断a是否等于"world",如果不等于则继续使用>操作符判断a是否大于"world",如果大于则输出"You win.",否则输出"You failed."。最后将字符串a赋值为" world"并输出。