C++ 字符串声明
外观
简介[编辑 | 编辑源代码]
在C++中,字符串是用于存储和操作文本数据的基本数据类型。C++提供了两种主要的字符串表示方式:
- C风格字符串(字符数组)
- C++标准库中的
std::string
类
本章将详细介绍这两种字符串的声明方式、初始化方法及使用场景,帮助初学者和进阶开发者全面掌握字符串操作。
C风格字符串[编辑 | 编辑源代码]
C风格字符串本质上是字符数组,以空字符(\0
)作为结束符。
声明与初始化[编辑 | 编辑源代码]
以下是声明C风格字符串的几种方式:
// 方式1:显式声明字符数组
char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// 方式2:使用字符串字面量初始化
char str2[] = "Hello";
// 方式3:动态分配内存
char* str3 = new char[6];
strcpy(str3, "Hello");
示例与输出[编辑 | 编辑源代码]
#include <iostream>
#include <cstring>
int main() {
char greeting[] = "Hello";
std::cout << greeting << std::endl; // 输出: Hello
std::cout << "Length: " << strlen(greeting) << std::endl; // 输出: 5
return 0;
}
C++标准库字符串(std::string)[编辑 | 编辑源代码]
std::string
是C++标准库提供的字符串类,封装了动态内存管理和常用操作,更安全且易用。
声明与初始化[编辑 | 编辑源代码]
// 方式1:默认初始化
std::string s1;
// 方式2:使用字符串字面量初始化
std::string s2 = "Hello";
// 方式3:使用构造函数
std::string s3(5, 'A'); // 结果为 "AAAAA"
// 方式4:从C风格字符串转换
const char* cstr = "World";
std::string s4(cstr);
常用操作示例[编辑 | 编辑源代码]
#include <iostream>
#include <string>
int main() {
std::string name = "Alice";
name += " Smith"; // 字符串拼接
std::cout << name << std::endl; // 输出: Alice Smith
// 访问字符
std::cout << "First character: " << name[0] << std::endl; // 输出: A
// 查找子串
size_t pos = name.find("Smith");
if (pos != std::string::npos) {
std::cout << "Found 'Smith' at position: " << pos << std::endl;
}
return 0;
}
比较C风格字符串与std::string[编辑 | 编辑源代码]
特性 | C风格字符串 | std::string |
---|---|---|
内存管理 | 手动分配/释放 | 自动管理 |
安全性 | 易出现缓冲区溢出 | 边界检查 |
操作函数 | strcpy , strcat 等
|
成员函数(如append , substr )
|
实际应用场景[编辑 | 编辑源代码]
场景1:用户输入处理[编辑 | 编辑源代码]
使用std::string
安全地读取用户输入:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter your name: ";
std::getline(std::cin, input); // 读取整行
std::cout << "Hello, " << input << "!" << std::endl;
return 0;
}
场景2:文件路径操作[编辑 | 编辑源代码]
利用std::string
的成员函数处理文件路径:
#include <iostream>
#include <string>
int main() {
std::string path = "/home/user/docs/report.txt";
size_t slash_pos = path.find_last_of('/');
std::string filename = path.substr(slash_pos + 1);
std::cout << "Filename: " << filename << std::endl; // 输出: report.txt
return 0;
}
进阶话题[编辑 | 编辑源代码]
字符串视图(C++17)[编辑 | 编辑源代码]
std::string_view
提供对字符串的非拥有视图,避免不必要的拷贝:
#include <iostream>
#include <string_view>
void print(std::string_view sv) {
std::cout << sv << std::endl;
}
int main() {
print("Hello"); // 无需构造std::string
return 0;
}
性能考虑[编辑 | 编辑源代码]
使用
总结[编辑 | 编辑源代码]
- C风格字符串适合与旧代码或底层API交互,但需谨慎管理内存。
std::string
是大多数场景下的首选,提供丰富的功能和安全性。- 现代C++(C++17+)引入
std::string_view
进一步优化性能。