4.4 std::string
C++ 程序通常使用 std::string 来处理文本。一个 std::string 对象知道自己的长度,可以在追加内容时自动变长,也提供了搜索、截取、编辑等常用方法。
cpp
#include <iostream>
#include <string>
int main() {
std::string name = "Ada";
std::cout << "Hello, " << name << std::endl;
return 0;
}使用 size() 或 length() 可以得到字符串中字符的个数。对 std::string 来说,它们含义相同。
cpp
std::string word = "program";
std::cout << word.size() << std::endl; // 7
std::cout << word.length() << std::endl; // 7需要访问单个字符时,可以使用下标。
cpp
std::cout << word[0] << std::endl; // p
std::cout << word[word.size() - 1] << std::endl; // m字符串下标也从 0 开始,和数组一样。front() 返回第一个字符,back() 返回最后一个字符。
cpp
std::cout << word.front() << std::endl;
std::cout << word.back() << std::endl;字符串可以用 + 或 += 拼接。
cpp
std::string first = "Grace";
std::string last = "Hopper";
std::string full = first + " " + last;
full += "!";字符串可以用 ==、!=、<、> 比较。大小关系按照字典序,也就是基于字符编码的顺序来比较。
cpp
if (password == "leaflet") {
std::cout << "ok" << std::endl;
}
if ("apple" < "banana") {
std::cout << "apple comes first" << std::endl;
}使用 find() 查找字符或子串。它会返回第一次出现的位置;如果没找到,会返回 std::string::npos。
cpp
std::string email = "[email protected]";
std::size_t at = email.find('@');
if (at != std::string::npos) {
std::cout << "@ 的下标是 " << at << std::endl;
}rfind() 从右往左查找,适合寻找最后一次出现的位置。
cpp
std::size_t dot = email.rfind('.');使用 substr(start, count) 可以复制字符串中的一部分。
cpp
std::string domain = email.substr(at + 1); // example.com
std::string user = email.substr(0, at); // student需要修改文本时,可以使用 insert()、erase() 和 replace()。
cpp
std::string label = "C++";
label.insert(0, "Learn ");
label.replace(0, 5, "Practice");
label.erase(label.size() - 3);当输入内容可能包含空格时,使用 std::getline() 读取整行。如果前面刚用过 std::cin >>,可能需要先处理遗留的换行符,再调用 std::getline()。
cpp
std::string sentence;
std::getline(std::cin, sentence);范围 for 循环可以很方便地逐个访问字符串中的字符。
cpp
for (char ch : sentence) {
std::cout << ch << std::endl;
}正在加载交互实验...
正在加载概念检查...
正在加载本节练习...