Files
XCEngine/docs/api/containers/string/substring.md

44 lines
1.4 KiB
Markdown
Raw Normal View History

# String::Substring
```cpp
String Substring(SizeType pos, SizeType len = npos) const;
```
返回从位置 `pos` 开始、长度为 `len` 的子字符串。如果 `len` 省略或为 `npos`,则返回从 `pos` 到字符串末尾的所有字符。
**参数:**
- `pos` - 子字符串的起始位置(从 0 开始)
- `len` - 子字符串的长度,默认为 `npos`(即到字符串末尾)
**返回:** 新的 String 对象,包含指定的子字符串
**复杂度:** O(n),其中 n 为子字符串的长度
**示例:**
```cpp
#include "XCEngine/Core/Containers/String.h"
#include <iostream>
int main() {
XCEngine::Containers::String s("Hello World");
XCEngine::Containers::String sub1 = s.Substring(6); // 从位置6到末尾
std::cout << sub1.CStr() << std::endl; // 输出: World
XCEngine::Containers::String sub2 = s.Substring(6, 5); // 从位置6开始长度5
std::cout << sub2.CStr() << std::endl; // 输出: World
XCEngine::Containers::String sub3 = s.Substring(0, 5); // 从位置0开始长度5
std::cout << sub3.CStr() << std::endl; // 输出: Hello
XCEngine::Containers::String sub4 = s.Substring(6, 100); // len超过剩余长度自动截断
std::cout << sub4.CStr() << std::endl; // 输出: World
return 0;
}
```
## 相关文档
- [String 总览](string.md) - 返回类总览