字符串
C++ 中有两种处理字符串的方式:C 风格字符串和 string 类。
string 类(推荐)
Section titled “string 类(推荐)”定义和初始化
Section titled “定义和初始化”#include <string>using namespace std;
string s1 = "Hello";string s2 = "World";string s3; // 空字符串string s = "Hello";cout << s.length() << endl; // 输出:5cout << s.size() << endl; // 输出:5(与 length() 相同)string s = "Hello";cout << s[0] << endl; // 输出:Hcout << s[4] << endl; // 输出:ostring s1 = "Hello";string s2 = " World";string s3 = s1 + s2; // 结果:Hello World
s1 += "!"; // s1 现在是 "Hello!"string s1 = "Hello";string s2 = "Hello";string s3 = "World";
if (s1 == s2) { cout << "s1 和 s2 相等" << endl;}
if (s1 != s3) { cout << "s1 和 s3 不相等" << endl;}string s = "Hello World";size_t pos = s.find("World");
if (pos != string::npos) { cout << "找到了,位置是: " << pos << endl;}string s = "Hello World";string sub = s.substr(6, 5); // 从位置 6 开始,取 5 个字符cout << sub << endl; // 输出:Worldstring name;
// 读取一个单词(遇空格停止)cin >> name;
// 读取整行(包含空格)getline(cin, name);
cout << "你好, " << name << endl;C 风格字符串
Section titled “C 风格字符串”char str[] = "Hello";char str2[10] = "World";
// 获取长度int len = strlen(str);
// 复制strcpy(str2, str);
// 拼接strcat(str, " World");
// 比较if (strcmp(str, str2) == 0) { cout << "相等" << endl;}常见操作示例
Section titled “常见操作示例”#include <algorithm>#include <string>using namespace std;
string s = "Hello";
// 转换为小写transform(s.begin(), s.end(), s.begin(), ::tolower);cout << s << endl; // 输出:hello
// 转换为大写transform(s.begin(), s.end(), s.begin(), ::toupper);cout << s << endl; // 输出:HELLO#include <algorithm>#include <string>using namespace std;
string s = " Hello World ";
// 去除前导空格s.erase(0, s.find_first_not_of(' '));
// 去除尾部空格s.erase(s.find_last_not_of(' ') + 1);
cout << s << endl; // 输出:Hello World- 优先使用
string类,而不是 C 风格字符串 string类更安全、更方便- 使用
getline()来读取包含空格的字符串