C++ string类提供构造、赋值、访问、查找、替换等丰富操作,通过实例演示了长度获取、子串提取、内容替换等功能,并推荐使用stringstream或reserve提升大量字符串拼接效率,同时介绍string::npos用于表示查找失败,以及stoi/to_string等函数实现字符串与数值转换。

C++
string类提供了丰富的功能,用于处理字符串。 掌握这些方法能极大提高代码效率和可读性。下面将介绍一些常用的字符串处理方法,并结合实际例子进行说明。
解决方案
C++
string类提供了强大的字符串操作能力。以下是一些常用的方法:
-
构造函数:
string s;
(默认构造,空字符串),string s = "hello";
(用C风格字符串初始化),string s(n, 'a');
(用n个字符 'a' 初始化),string s(another_string);
(拷贝构造). -
赋值:
s = "world";
,s.assign("C++");,s.assign(another_string);
,s.assign(n, 'b');
. -
访问:
s[i]
(访问索引为 i 的字符,不进行越界检查),s.at(i)
(访问索引为 i 的字符,进行越界检查,越界会抛出异常). -
长度:
s.length()
或s.size()
(返回字符串长度). -
容量:
s.capacity()
(返回当前分配的内存大小,可能大于字符串长度),s.reserve(n)
(预分配至少能容纳 n 个字符的空间,避免频繁重新分配内存),s.shrink_to_fit()
(释放多余的内存). -
添加:
s += "!";
,s.append(" more");,s.push_back('c');. -
插入:
s.insert(pos, "new");
(在 pos 位置插入字符串 "new"),s.insert(pos, another_string);
,s.insert(pos, n, 'x');
(在 pos 位置插入 n 个字符 'x'). -
删除:
s.erase(pos, len);
(从 pos 位置开始删除 len 个字符),s.clear()
(清空字符串). -
替换:
s.replace(pos, len, "replacement");
(从 pos 位置开始,替换 len 个字符为 "replacement"),s.replace(pos, len, another_string);
. -
查找:
s.find("substring");(查找 "substring" 第一次出现的位置,返回索引,找不到返回string::npos
),s.rfind("substring");(从后往前查找),s.find_first_of("chars");(查找第一个出现在 "chars" 中的字符的位置),s.find_last_of("chars");(查找最后一个出现在 "chars" 中的字符的位置). -
子串:
s.substr(pos, len);
(返回从 pos 位置开始,长度为 len 的子串). -
比较:
s1 == s2
,s1 != s2
,s1 < s2
,s1 > s2
,s.compare(another_string);
(返回 0 表示相等,小于 0 表示 s 小于 another_string,大于 0 表示 s 大于 another_string). -
转换为C风格字符串:
s.c_str()
(返回指向C风格字符串的指针,注意生命周期问题).
#include#include int main() { std::string str = "Hello, World!"; // 长度 std::cout << "Length: " << str.length() << std::endl; // 查找 size_t pos = str.find("World"); if (pos != std::string::npos) { std::cout << "'World' found at position: " << pos << std::endl; } // 子串 std::string sub = str.substr(7, 5); // "World" std::cout << "Substring: " << sub << std::endl; // 替换 str.replace(7, 5, "C++"); std::cout << "Replaced string: " << str << std::endl; return 0; }
如何高效地拼接大量字符串?
使用
+=或
append在循环中拼接字符串,尤其是在拼接大量字符串时,效率可能较低,因为每次操作都可能涉及内存重新分配。 更好的做法是预先分配足够的内存,或者使用
stringstream。
立即学习“C++免费学习笔记(深入)”;
动态WEB网站中的PHP和MySQL详细反映实际程序的需求,仔细地探讨外部数据的验证(例如信用卡卡号的格式)、用户登录以及如何使用模板建立网页的标准外观。动态WEB网站中的PHP和MySQL的内容不仅仅是这些。书中还提到如何串联JavaScript与PHP让用户操作时更快、更方便。还有正确处理用户输入错误的方法,让网站看起来更专业。另外还引入大量来自PEAR外挂函数库的强大功能,对常用的、强大的包
#include#include #include int main() { std::stringstream ss; for (int i = 0; i < 1000; ++i) { ss << "Number: " << i << " "; } std::string result = ss.str(); std::cout << result.substr(0, 100) << "..." << std::endl; // 输出部分结果 return 0; }
使用
stringstream避免了频繁的内存重新分配,提高了效率。 另一种方法是使用
reserve预先分配足够的内存。
string::npos
是什么?有什么用?
string::npos是
string类的一个静态成员常量,通常被定义为
-1或
size_t类型的最大值。 它表示“未找到”或“不存在”的位置。
find函数在查找失败时会返回
string::npos。
#include#include int main() { std::string str = "Hello"; size_t pos = str.find("World"); if (pos == std::string::npos) { std::cout << "'World' not found in the string." << std::endl; } else { std::cout << "'World' found at position: " << pos << std::endl; } return 0; }
如何将 string
转换为 int
或 float
?反之呢?
C++11 提供了
std::stoi,
std::stof,
std::stod等函数用于将字符串转换为数值类型。 反过来,可以使用
std::to_string将数值类型转换为字符串。
#include#include int main() { std::string str_int = "123"; std::string str_float = "3.14"; int num_int = std::stoi(str_int); float num_float = std::stof(str_float); std::cout << "Integer: " << num_int << std::endl; std::cout << "Float: " << num_float << std::endl; std::string new_str_int = std::to_string(num_int * 2); std::string new_str_float = std::to_string(num_float * 2); std::cout << "New Integer String: " << new_str_int << std::endl; std::cout << "New Float String: " << new_str_float << std::endl; return 0; }
需要注意的是,如果字符串不能正确转换为数值类型,
std::stoi,
std::stof,
std::stod会抛出异常,因此需要进行适当的错误处理。








