c++字符串遇到标点符号切片
时间: 2025-03-05 16:32:51 浏览: 51
### 实现C++中按标点符号分割字符串
在C++中处理字符串并按照特定字符(如标点符号)进行切割可以通过多种方式完成。一种常见方法是利用标准库中的`sstream`头文件来辅助解析,另一种更直接的方式则是通过遍历字符串并手动识别分隔符。
对于基于标点符号的字符串拆分操作,可以创建一个函数用于检测是否遇到了指定作为分隔符的标点符号集合内的成员。下面是一个具体的例子:
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <cctype> // For ispunct function
using namespace std;
// 定义split函数,参数为待分割的字符串以及存储结果的容器
void split(const string& str, vector<string>& tokens) {
size_t start = 0;
size_t end = str.find_first_of(".,!?;:");
while (end != string::npos){
if(end > start || !str[start]) // 防止连续标点导致空串加入tokens
tokens.push_back(str.substr(start, end - start));
start = str.find_first_not_of(".,!?;:", end);
if(start == string::npos) break;
end = str.find_first_of(".,!?;", start);
}
if(start < str.length()) // 处理最后一部分
tokens.push_back(str.substr(start));
}
int main(){
string input = "Hello, world! This is a test.";
vector<string> words;
split(input, words);
cout << "Split result:" << endl;
for(auto word : words){
cout << word << endl;
}
return 0;
}
```
上述代码展示了如何定义一个名为`split`的功能函数[^1],该函数接收两个参数——一个是目标字符串,另一个是用来保存分割后的子串列表。这里使用了`find_first_of()`和`find_first_not_of()`这两个成员函数分别寻找下一个标点位置及其之后的第一个非标点字符的位置。此外,在循环外还加入了额外判断以确保最后一个片段也能被正确添加到结果集中。
#### 注意事项
- `ispunct()` 函数可用于测试单个字符是否属于任何类型的标点符号类别。
- 如果希望支持更多种类的标点或自定义分隔符,则可以在调用`find_first_of()`时传入相应的字符集。
阅读全文
相关推荐



















