std::string 提供了一种高效且简单的方式来操作字符串,不仅可以进行轻松的字符串连接,还能完成长度计算、字符访问和后缀处理等处理任务。本文将优化精进地分析 C++ 中的 std::string 和其采用的常见函数,尤其是 size() 函数,并提供相关优化解释和知识拓展。
C++ 参考手册

C++ 中, std::string 是一种是封装类,能夠提供对字符串进行操作的简单方式。和传统的 C 风格字符串(char[])相比,它更加高效和安全,提供了丰富的语法支持。
典型例如:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "hello";
string s2 = "world";
string s3 = s1 + " " + s2; // 字符串相连
cout << s3 << endl; // 输出:hello world
return 0;
}上面过程体现了 C++ 字符串的连接功能,显示了它的自然语法背后的高效。
size() 函数基础在字符串操作中,实现字符串长度计算是一项基础而重要的功能。C++ 中的 std::string 提供了两个全程等任的函数:size() 和 length(),它们用于计算字符串的长度,返回字符串中的字符数量。
例如:
string s = "hello";
cout << s.size() << endl; // 输出:5
cout << s.length() << endl; // 输出:5注意:size() 和 length() 是等任的,可以任意使用任一个。
在下面这段代码中,实现了通过 size() 函数来计算一些不同内容字符串的长度。
代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s; // 完全空字符串
string s1 = "hello"; // 有 5 个字符
string s2 = "hello world"; // 包含空格共 11 个字符
string s3 = "12lab!~ "; // 包括空格共 14 个字符
cout << "s:" << s.size() << endl;
cout << "s1:" << s1.size() << endl;
cout << "s2:" << s2.size() << endl;
cout << "s3:" << s3.size() << endl;
return 0;
}运行结果:
s:0
s1:5
s2:11
s3:14分析:
s 为空,因此返回长度 0。s1 包含 5 个字符,因此返回长度 5。s2 含有一个空格,因此返回总长度 11。s3 包含多种符号和空格,返回总长度 14。从运行结果可以看出,size() 会正确计算字符串中的字符总数,包括字母、数字,空格,和其他符号。
C++ 允许通过下标访问字符串中的单个字符:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdef";
for (int i = 0; i < s.size(); i++) {
cout << s[i] << " "; // 通过下标访问字符,并传递打印
}
return 0;
}运行结果:
a b c d e f分析:
size() 返回的长度为止,通过下标每次选取字符。通过下标访问和 size() 相结合,可以高效地进行字符级的解析:
例如:给定字符串,计算其中大写字母的总数:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "HelloWorld123";
int count = 0;
for (int i = 0; i < s.size(); i++) {
if (isupper(s[i])) {
count++;
}
}
cout << "Number of uppercase letters: " << count << endl;
return 0;
}运行结果:
Number of uppercase letters: 2std::string 还允许通过迭代器实现字符的访问:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdef";
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
return 0;
}运行结果:
a b c d e fat() 函数会对下标进行范围检查,能够更好地确保安全:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "abcdef";
try {
cout << s.at(0) << endl; // 正常输出第一个字符
cout << s.at(10) << endl; // 越界,抛出异常
} catch (out_of_range &e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}运行结果:
a
Exception: basic_string::at: __n (which is 10) >= this->size() (which is 6)分析:
s.at(0) 正常返回第一个字符。s.at(10) 超出范围,抛出 out_of_range 异常,确保程序不会因为非法访问崩溃。本文从基础到进阶详细解析了 C++ 中 std::string 的功能,尤其是 size() 函数的应用及其与下标访问、迭代器、at() 方法的结合使用。同时补充了许多进阶拓展内容,包括安全性检查和高效字符串操作的实践。通过这些知识点,相信读者能够更加灵活、高效、安全地处理 C++ 字符串操作。如果对某些部分有疑问或需要更深入的探讨,可以进一步结合具体场景和实践需求展开!