string分割c++
时间: 2024-06-16 20:01:09 浏览: 109
在C++中,`std::string` 类型的字符串分割通常涉及到将一个字符串分解成多个子串,这可以通过不同的方法实现,如使用 `std::getline()`、`substr()` 函数或者自定义迭代器。这里以 `std::getline()` 和 `substr()` 为例:
1. **使用 `std::getline()`**:
`std::getline` 从输入流中逐行读取数据,并且可以用来处理包含空格或其他分隔符的字符串。例如,如果有一个逗号分隔的字符串列表,你可以这样做:
```cpp
std::ifstream file("data.txt");
std::string line;
std::vector<std::string> words;
while (std::getline(file, line)) {
size_t pos = 0;
std::string word;
while ((pos = line.find(",")) != std::string::npos) {
word = line.substr(0, pos);
words.push_back(word);
line.erase(0, pos + 1); // 移除已找到的分隔符
}
words.push_back(line); // 添加最后一部分,如果没有分隔符
}
```
2. **使用 `substr()` 和 `find()`**:
如果你知道要分割的字符(如空格或特定字符),可以使用 `substr()` 和 `find()` 方法循环提取子串:
```cpp
std::string str = "Hello World, C++ Programming";
std::vector<std::string> parts;
size_t start = 0;
while (start < str.size()) {
size_t end = str.find(' ', start);
if (end == std::string::npos) { // 如果没有找到空格,直到字符串末尾
end = str.size();
}
parts.push_back(str.substr(start, end - start));
start = end + 1; // 更新起始位置
}
parts.erase(parts.begin()); // 去除最后一个可能的空字符串
```
**相关问题--:**
1. `std::getline()` 和 `substr()` 分别用于什么场景?
2. 如何用C++实现不区分空格的连续字符串分割?
3. 如果我想使用其他分隔符,如何修改上述代码?
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)