std::string 是 C++ 标准库提供的字符串类型,声明在 <string> 中。它会自动管理字符数量和存储空间,比手动维护以 \0 结尾的字符数组更适合日常文本处理。
创建、输入与输出
字符串可以直接用文本初始化,也可以通过赋值修改。cin >> text 只读取一个单词;需要保留空格时,应使用 getline(cin, text) 读取整行。
string language = "C++";
string topic;
getline(cin, topic);
cout << language << ": " << topic << endl;长度与状态
size() 和 length() 都返回字符数量,结果类型是 size_t;empty() 判断字符串是否没有字符。它们都不会修改原字符串。
string text = "Leaflet";
cout << text.size() << endl; // 7
cout << text.length() << endl; // 7
cout << boolalpha << text.empty() << endl; // false访问单个字符
text[index] 通过从 0 开始的下标访问字符;front() 和 back() 分别访问首字符与末字符。at(index) 也按下标访问,但会检查是否越界。
string text = "Leaflet";
cout << text[0] << endl; // L
cout << text.front() << endl; // L
cout << text.back() << endl; // t
text[0] = 'l';追加与插入
append(value) 和 += 在末尾追加内容;insert(position, value) 从指定下标前插入内容。这些方法修改的是原字符串。
string text = "Leaf";
text.append("let"); // Leaflet
text += " course"; // Leaflet course
text.insert(7, " C++"); // Leaflet C++ course截取、查找与修改
substr(start, count) 返回一个新字符串。find(value) 返回第一次匹配的起始位置;找不到时返回 string::npos。replace(start, count, value) 替换一段字符,erase(start, count) 删除一段字符。
string text = "Leaflet course";
string name = text.substr(0, 7); // Leaflet
size_t position = text.find("course"); // 8
if (position != string::npos) {
text.replace(position, 6, "lab"); // Leaflet lab
}
text.erase(7, 4); // LeafletC++ string 方法实验台
选择一个方法,观察调用表达式、是否修改原字符串,以及返回值或修改后的字符布局。
text.size();返回字符数量,空格也算一个字符。
比较字符串
== 和 != 判断内容是否相同;compare() 返回负数、0 或正数,分别表示当前字符串排在参数之前、相同或之后。
string first = "apple";
string second = "banana";
if (first != second && first.compare(second) < 0) {
cout << first << " comes first" << endl;
}知识测验
知识测验
知识测验
生成用户名
读取由单个单词组成的名和姓,使用 std::string 生成用户名“名.姓”,并同时输出用户名长度。
- 使用 cin 分别读取 first 和 last。
- 拼接 first + '.' + last。
- 输出用户名以及 username.size()。
提取邮箱域名
读取一个邮箱样式字符串,提取 @ 后面的域名;缺少 @ 或域名为空时输出错误。
- 使用 find 查找 @ 的位置。
- 检查返回值是否为 string::npos,并确认 @ 后还有字符。
- 使用 substr(position + 1) 提取并输出域名。
实现一次文本替换
读取原文本、要查找的片段和替换片段,只替换第一次出现的位置。
- 使用 find 获得第一次匹配的位置。
- 未找到时保持原文本并输出提示。
- 找到时调用 replace(position, old_text.size(), new_text) 并输出结果。