c++string用法大全
时间: 2024-11-05 21:11:35 浏览: 28
`std::string`是C++标准库中的一个基础类型,它是一个动态数组,用于存储文本数据。以下是`std::string`的一些常用用法:
1. **创建字符串**:
- 使用构造函数:`std::string str("Hello");` 或 `std::string str = "Hello";`
- 直接赋值:`std::string anotherStr; anotherStr = "World";`
2. **访问字符**:
- 指定索引:`char ch = str[0];`(从0开始计数)
- 遍历:`for (int i = 0; i < str.length(); ++i) { char c = str[i]; }`
3. **长度操作**:
- 获取长度:`size_t len = str.length();`
- 空字符串检查:`if (str.empty()) { ... }`
4. **连接和复制**:
- 连接:`std::string result = str + " " + anotherStr;`
- 复制:`std::string copy(str);`
5. **修改和删除**:
- 修改单个字符:`str[0] = 'H';`
- 删除指定范围:`str.erase(startIndex, length);`
6. **查找和替换**:
- 查找子串:`size_t pos = str.find("World");`
- 替换子串:`str.replace(pos, 5, "Universe");`
7. **成员函数**:
- `substr(start, length)` 提取子串
- `append(newStr)` 向末尾添加
- `insert(index, newStr)` 在指定位置插入
8. **安全性注意事项**:
- 对于索引操作,要避免越界,因为超出范围会触发未定义的行为。
阅读全文
相关推荐
















