在空格后用C ++拆分字符串,如果超过1个空格则将其留在字符串中

时间:2015-09-22 15:38:35

标签: c++

我需要用单个空格分割字符串并将其存储到字符串数组中。我可以使用fonction boost实现这一点:split,但我无法实现的是:

如果有多个空格,我想将空间整合到矢量

例如: (下划线表示空格)

This_is_a_string. gets split into: A[0]=This A[1]=is A[2]=a A[3]=string.

This__is_a_string. gets split into: A[0]=This A[1] =_is A[2]=a A[4]=string.

我该如何实现?

由于

2 个答案:

答案 0 :(得分:0)

为此,您可以使用findsubstr函数的组合进行字符串解析。

假设到处都只有一个空格,那么代码就是:

while (str.find(" ") != string::npos)
{
  string temp = str.substr(0,str.find(" "));
  ans.push_back(temp);
  str = str.substr(str.find(" ")+1);
}

您提出的其他请求表明我们在确定它没有查看前导空格后调用find函数。为此,我们可以遍历前导空格来计算有多少,然后调用find函数从上面搜索。要在find位置之后使用x函数(因为有x个前导空格),调用将为str.find(" ",x)

您还应该处理角落情况,例如整个字符串在任何时候由空格组成。在这种情况下,当前表单中的while条件不会终止。也可以在那里添加x参数。

答案 1 :(得分:0)

这绝不是最优雅的解决方案,但它将完成工作:

void bizarre_string_split(const std::string& input, 
    std::vector<std::string>& output)
{
    std::size_t begin_break = 0;
    std::size_t end_break = 0;

    // count how many spaces we need to add onto the start of the next substring
    std::size_t append = 0;

    while (end_break != std::string::npos)
    {
        std::string temp;
        end_break = input.find(' ', begin_break);
        temp = input.substr(begin_break, end_break - begin_break);
        // if the string is empty it is because end_break == begin_break
        // this happens because the first char of the substring is whitespace
        if (!temp.empty())
        {
            std::string temp2;
            while (append)
            {
                temp2 += ' ';
                --append;
            }
            temp2 += temp;
            output.push_back(temp2);
        }
        else
        {
            ++append;
        }
        begin_break = end_break + 1;
    }
}
相关问题