C++用空格和标点符号分隔字符串

C++ split string with space and punctuation chars

本文关键字:分隔 字符串 标点符号 空格 C++      更新时间:2023-10-16

我想用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;