c++ - 在 C++ 中使用多个定界符拆分字符串

标签 c++ string split token delimiter

<分区>

所以我必须将短语:“大家好!这是:COSC-1436,SP18”拆分成单独的标记,去掉任何标点符号减去破折号。所以输出应该是:

你好

大家

这个

COSC-1436

SP18

然后我必须加密我得到的每个 token 。我只是在使用多个定界符时遇到问题。这是我目前拥有的。

函数原型(prototype): void tokenize(const string&, const string&, vector<string>&);

函数调用: tokenize(code, " .,:;!?", tokens);

函数定义:

void tokenize(const string& str, const string& delim, vector<string>& tokens)
{
    int tokenStart = 0;

    int delimPos = str.find_first_of(delim);

    while(delimPos != string::npos)
    {
        string tok = str.substr(tokenStart, delimPos - tokenStart);

        tokens.push_back(tok);

        delimPos++;

        tokenStart = delimPos;

        delimPos = str.find_first_of(delim, delimPos);

        if(delimPos == string::npos)
        {
            string tok = str.substr(tokenStart, delimPos - tokenStart);

            tokens.push_back(tok);
        }   
    }
}

唯一的问题是现在在程序遇到标点符号的地方有标记作为空格。有什么建议吗?

最佳答案

找到定界符后,您应该将子字符串的开头移动到 first_not_of 定界符处。基本改变:

delimPos++;

到:

delimPos = str.find_first_not_of(delim, delimPos + 1);

这将确保当您有 2 个或更多定界符时,delimPos 会移到最后一个之后。

或者你可以试试这个:

#include <iostream> 
#include <string>

int main()
{
    std::string str = "Hello, everyone! This is: COSC-1436, SP18";
    std::string const delims{ " .,:;!?" };

    size_t beg, pos = 0;
    while ((beg = str.find_first_not_of(delims, pos)) != std::string::npos)
    {
        pos = str.find_first_of(delims, beg + 1);
        std::cout << str.substr(beg, pos - beg) << std::endl;
    }

    return 0;
}

https://ideone.com/LJota9

Hello
everyone
This
is
COSC-1436
SP18

关于c++ - 在 C++ 中使用多个定界符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49201654/

相关文章:

html - 如何强制包装没有任何空白的长字符串?

java - 格式化固定格式的文本文件行

python - 如何在不使用空格作为单词分隔符的语言(如中文)上执行 Python split()?

c# - 在 C# 中快速去/交错数组

c++ - Q_ENUMS 在 QML 中是 "undefined"吗?

c++ - Windows 上 native C++ 应用程序中的自动死代码检测?

python - 将逗号分隔的数据转换为不带 CSV 模块的列表

r - 给定数字和 n 组,如何将数字随机分成多个数字?

c++ - '../controlpanel.ui' 需要 Qt : No rule to make target 'ui_controlpanel.h' ,。停止

c++ - 在 .cpp 标准中包含文件