C++用空格和标点符号分隔字符串
C++ split string with space and punctuation chars
我想用C++拆分一个包含空格和标点符号的字符串。
例如str = "This is a dog; A very good one."
我想得到"This"is"a"dog"a"very"good"one"1比1。
使用getline只使用一个分隔符非常容易,但我不知道所有的分隔符。它可以是任何标点符号字符。
注意:我不想使用Boost!
使用带lambda的std::find_if()
来查找分隔符。
auto it = std::find_if(str.begin(), str.end(), [] (const char element) -> bool {
return std::isspace(element) || std::ispunct(element);})
因此,从第一个位置开始,您将找到第一个有效的令牌。你可以使用
index = str.find_first_not_of (yourDelimiters);
然后你必须找到这之后的第一个分隔符,这样你就可以进行
delimIndex = str.substr (index).find_first_of (yourDelimiters);
你的第一个单词就是
// since delimIndex will essentially be the length of the word
word = str.substr (index, delimIndex);
然后截断字符串并重复。当然,您必须处理find_first_not_of和find_first_of返回npos的所有情况,这意味着没有找到字符,但我认为这已经足够开始了。
顺便说一句,我并不是说这是最好的方法,但它有效。。。
vmpstr的解决方案可以工作,但可能有点乏味。几个月前,我写了一个C库,可以满足你的需求。http://wiki.gosub100.com/doku.php?id=librerias:c:cadenas
文档是用西班牙语编写的(抱歉)。
它不需要外部依赖关系。尝试使用splitWithChar()函数。
使用示例:
#include "string_functions.h"
int main(void){
char yourString[]= "This is a dog; A very good one.";
char* elementsArray[8];
int nElements;
int i;
/*------------------------------------------------------------*/
printf("Character split test:n");
printf("Base String: %sn",yourString);
nElements = splitWithChar(yourString, ' ', elementsArray);
printf("Found %d element.n", nElements);
for (i=0;i<nElements;i++){
printf ("Element %d: %sn", i, elementsArray[i]);
}
return 0;
}
原来的字符串"yourString"是在使用splitWithChar()后修改的,所以要小心。
祝你好运:)
CPP与JAVA不同,它不提供通过分隔符分隔字符串的优雅方式。您可以使用boost库进行同样的操作,但如果您想避免它,手动逻辑就足够了。
vector<string> split(string s) {
vector<string> words;
string word = "";
for(char x: s) {
if(x == ' ' or x == ',' or x == '?' or x == ';' or x == '!'
or x == '.') {
if(word.length() > 0) {
words.push_back(word);
word = "";
}
}
else
word.push_back(x);
}
if(word.length() > 0) {
words.push_back(word);
}
return words;
相关文章:
- 如何分隔字符串并将标记传递给方法
- C++ 用空格和逗号分隔字符串
- 如何将整数值解析为逗号分隔字符串中的单独 int 变量?
- 如何分隔字符串并将每个部分存储在不同的向量中
- 如何按特定分隔符分隔字符串
- 逗号分隔字符串的总和,例如 O(n) 中的 4,1,3
- 如何使用符号分隔字符串而不是空格的输入字符串流
- C++中将不同类型的变量列表连接到逗号分隔字符串的最快方法是什么?
- C++ sscanf 空格分隔字符串
- 在C++中分隔字符串并存储到数组中的最佳方法
- 使用 find_first_of() 和 substr() 分隔字符串,但我得到的输出不正确
- 正在分析逗号分隔字符串中的整数
- 分析分隔字符串
- 用空格分隔字符串的最简单方法
- 分隔字符串的最佳ASCII字符是什么
- C++用空格和标点符号分隔字符串
- c#中分隔字符串中的数字和单位
- 如何基于标记分隔字符串
- c++使用wstring拆分unicode分隔字符串
- 如何在C++中用逗号分隔字符串