跳转到内容

字符串

C++ 中有两种处理字符串的方式:C 风格字符串和 string 类。

#include <string>
using namespace std;
string s1 = "Hello";
string s2 = "World";
string s3; // 空字符串
string s = "Hello";
cout << s.length() << endl; // 输出:5
cout << s.size() << endl; // 输出:5(与 length() 相同)
string s = "Hello";
cout << s[0] << endl; // 输出:H
cout << s[4] << endl; // 输出:o
string 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; // 输出:World
string name;
// 读取一个单词(遇空格停止)
cin >> name;
// 读取整行(包含空格)
getline(cin, name);
cout << "你好, " << name << endl;
char str[] = "Hello";
char str2[10] = "World";
// 获取长度
int len = strlen(str);
// 复制
strcpy(str2, str);
// 拼接
strcat(str, " World");
// 比较
if (strcmp(str, str2) == 0) {
cout << "相等" << endl;
}
#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() 来读取包含空格的字符串