字符串
C++ 中的 std::string 内容
std::string 内容std::string str = "Hello"; char firstChar = str[0]; // 访问第一个字符 'H'std::string str = "Hello"; str += ", World!"; // 自动扩展内存,不需手动管理std::string str = "Hello"; size_t len = str.length(); // 返回字符串的长度std::string str1 = "Hello"; std::string str2 = " World"; std::string result = str1 + str2; // 拼接字符串,结果为 "Hello World"std::string str = "Hello World"; size_t pos = str.find("World"); // 查找 "World" 在字符串中的位置std::string str = "Hello World"; std::string sub = str.substr(6, 5); // 提取从索引 6 开始的 5 个字符,结果为 "World"std::string str = "Hello World"; str.replace(6, 5, "C++"); // 把 "World" 替换为 "C++",结果为 "Hello C++"
std::string str = "Hello"; const char* c_str = str.c_str(); // 转换为 C 风格字符串const char* c_str = "Hello"; std::string str = c_str; // 从 C 风格字符串构造 std::string
std::string str1 = "Hello"; std::string str2 = "World"; std::string result = str1 + " " + str2; // 结果为 "Hello World" if (str1 == "Hello") { // 比较字符串内容是否相等 }
std::string str = "Hello"; // 使用下标 for (size_t i = 0; i < str.size(); ++i) { std::cout << str[i] << " "; } // 使用迭代器 for (auto it = str.begin(); it != str.end(); ++it) { std::cout << *it << " "; }std::string str = "Hello"; str.resize(10, 'X'); // 将字符串扩展为长度 10,用 'X' 填充新位置,结果为 "HelloXXXXX"
总结
Last updated