108 lines
2.9 KiB
Markdown
108 lines
2.9 KiB
Markdown
# String
|
||
|
||
**命名空间**: `XCEngine::Containers`
|
||
|
||
**类型**: `class`
|
||
|
||
**头文件**: `XCEngine/Containers/String.h`
|
||
|
||
**描述**: 动态字符串类,提供 UTF-8 编码的字符串操作。
|
||
|
||
## 概述
|
||
|
||
`String` 是一个自定义动态字符串类,提供常见的字符串操作功能,支持拷贝构造、移动构造和多种字符串操作方法。
|
||
|
||
## 类型别名
|
||
|
||
| 别名 | 类型 | 描述 |
|
||
|------|------|------|
|
||
| `SizeType` | `size_t` | 大小类型 |
|
||
|
||
## 常量
|
||
|
||
| 常量 | 值 | 描述 |
|
||
|------|-----|------|
|
||
| `static constexpr SizeType npos` | `static_cast<SizeType>(-1)` | 无效位置标识 |
|
||
|
||
## 公共方法
|
||
|
||
| 方法 | 描述 |
|
||
|------|------|
|
||
| [Constructor](constructor.md) | 构造字符串实例 |
|
||
| [Destructor](destructor.md) | 析构函数 |
|
||
| [operator=](operator-assign.md) | 赋值运算符 |
|
||
| [operator+=](operator-plus-assign.md) | 追加字符串/字符 |
|
||
| [operator+](operator-plus.md) | 字符串连接 |
|
||
| [operator==](operator-equal.md) | 判断两个字符串是否相等 |
|
||
| [operator!=](operator-equal.md) | 判断两个字符串是否不相等 |
|
||
| [Substring](substring.md) | 获取子串 |
|
||
| [Trim](trim.md) | 去除首尾空白 |
|
||
| [ToLower/ToUpper](to-lower-upper.md) | 大小写转换 |
|
||
| [Find](find.md) | 查找子串位置 |
|
||
| [StartsWith](starts-with.md) | 检查前缀 |
|
||
| [EndsWith](ends-with.md) | 检查后缀 |
|
||
| [CStr](cstr.md) | 获取 C 字符串指针 |
|
||
| [Length/Capacity/Empty](size.md) | 获取尺寸信息 |
|
||
| [operator[]](operator-subscript.md) | 下标访问 |
|
||
| [Clear](clear.md) | 清空字符串 |
|
||
| [Reserve/Resize](reserve-resize.md) | 预留/调整容量 |
|
||
|
||
## std::hash 特化
|
||
|
||
```cpp
|
||
namespace std {
|
||
template<>
|
||
struct hash<XCEngine::Containers::String> {
|
||
size_t operator()(const XCEngine::Containers::String& str) const noexcept;
|
||
};
|
||
}
|
||
```
|
||
|
||
提供了 `std::hash<String>` 特化,使 `String` 可以作为 unordered_map 或 unordered_set 的键使用。
|
||
|
||
**实现算法:** DJB hash (Daniel J. Bernstein hash)
|
||
|
||
**算法细节:**
|
||
- 初始值:5381
|
||
- 对每个字符:`hash = hash * 33 + c`(等价于 `(hash << 5) + hash + c`)
|
||
|
||
**示例:**
|
||
```cpp
|
||
#include <XCEngine/Containers/String.h>
|
||
#include <unordered_map>
|
||
|
||
int main() {
|
||
std::unordered_map<XCEngine::Containers::String, int> map;
|
||
map["key1"] = 100;
|
||
map["key2"] = 200;
|
||
return 0;
|
||
}
|
||
```
|
||
|
||
## 使用示例
|
||
|
||
```cpp
|
||
#include <XCEngine/Containers/String.h>
|
||
|
||
// 基本用法
|
||
Containers::String str = "Hello";
|
||
str += ", World!";
|
||
|
||
// 字符串操作
|
||
Containers::String sub = str.Substring(0, 5); // "Hello"
|
||
bool hasPrefix = str.StartsWith("Hello");
|
||
bool hasSuffix = str.EndsWith("!");
|
||
|
||
// 查找
|
||
XCEngine::Containers::String::SizeType pos = str.Find("World"); // 返回 6
|
||
|
||
// 转换
|
||
Containers::String upper = str.ToUpper();
|
||
Containers::String lower = str.ToLower();
|
||
```
|
||
|
||
## 相关文档
|
||
|
||
- [Array](../array/array.md) - 动态数组
|
||
- [HashMap](../hashmap/hashmap.md) - 哈希表
|