std::string 是 C++ 标准库提供的字符串类类型,用来保存和操作一串字符。
std::string name = "Alice";
std::string是类型。name是这个类型的对象。"Alice"是用来初始化对象的文字内容。
使用它需要包含 <string>
#include <string>
如果还需要在终端输出,就再包含:
#include <iostream>
它是类,所以有构造函数。
下面是几种常用的创建方式,变量名彼此不同:
cpp
// 默认构造:创建一个空字符串对象
std::string s1;
// 使用文字初始化
std::string s2 = "Hello";
// 直接将参数传给构造函数
std::string s3("World");
// 创建包含 5 个 A 的字符串
std::string s4(5, 'A');
// 根据已有字符串对象,拷贝构造另一个对象
std::string s5 = s2;
| 对象 | 保存的内容 |
|---|---|
s1 |
"",空字符串 |
s2 |
"Hello" |
s3 |
"World" |
s4 |
"AAAAA" |
s5 |
"Hello" |
| 操作 | 作用 |
|---|---|
text.size() |
返回其中的 char 元素数量 |
text.empty() |
判断内容是否为空 |
text.clear() |
清空内容,对象本身仍然存在 |
text[0] |
访问第一个字符,要求字符串中存在这个字符 |
text.c_str() |
获取访问字符串字符数据的 const char* |
cpp
#include <iostream>
#include <string>
int main()
{
// 让 bool 值显示为 true / false,而不是 1 / 0
std::cout << std::boolalpha;
// 1. 默认构造一个空字符串对象
std::string text;
std::cout << "Initially empty: "
<< text.empty() << '\n';
// 2. 给已有对象赋值
text = "Hello";
std::cout << "After assignment: "
<< text << '\n';
// 3. 在原字符串后面追加文字
text += " World";
std::cout << "After append: "
<< text << '\n';
// 4. 查询长度:Hello 为 5,空格为 1,World 为 5
std::cout << "Length: "
<< text.size() << '\n';
// 5. 修改第一个字符
text[0] = 'h';
std::cout << "After change: "
<< text << '\n';
// 6. 拷贝构造另一个字符串对象
std::string copy = text;
// 修改副本,原对象的内容不变
copy[0] = 'H';
std::cout << "Original: " << text << '\n';
std::cout << "Copy: " << copy << '\n';
// 7. 通过 c_str() 提供的字符指针输出内容
std::cout << "C string: "
<< text.c_str() << '\n';
// 8. 清空内容,text 对象仍然存在
text.clear();
std::cout << "After clear: "
<< text.empty()
<< ", length: "
<< text.size() << '\n';
return 0;
}
cpp
Initially empty: true
After assignment: Hello
After append: Hello World
Length: 11
After change: hello World
Original: hello World
Copy: Hello World
C string: hello World
After clear: true, length: 0