【问题标题】:c++ splitting a string and getting the part coming after whitespacec ++拆分字符串并获取空格后的部分
【发布时间】:2013-12-28 00:37:11
【问题描述】:

我需要做一个字符串拆分,这样如果我有一个像下面这样的字符串

string foo="thisIsThe         Test     Input";

我需要在多个或单个 withspace 之后获取部分。在这种情况下,我需要获得"Test Input". 我知道我可以通过以下方式获得第一部分:

int index=foo.find(' ');
string subString=foo.substr(0,index);

但我不知道我该怎么做。有没有人可以帮助我?

【问题讨论】:

    标签: c++ string split


    【解决方案1】:

    std::find_first_not_of 接受一个位置参数,指示从哪里开始搜索。所以用它来查找第一个非空格,从第一个空格开始。

    int index=foo.find(' ');
    index=foo.find_first_not_of(' ', index);
    string subString=foo.substr(index);
    

    【讨论】:

    • 他只想要包含“测试输入”的部分。你应该从索引到结尾
    • @Ben-Voigt 如果一个字符串在空格之后不包含任何内容,它会给我错误吗?
    • @Ben-Voigt 还是空字符串?
    • @caesar:我不确定你得到的是 out_of_range 还是空字符串。如果您对此感到担心,请针对string::npos 测试index
    • 我想你得到了out_of_range。因为如果找不到文本,find_first_not_of 会返回 string::nposnpos 是字符串的最大大小
    【解决方案2】:

    您也可以通过 char 消除任何空格来复制到新字符串 char。 这将使使用 foo.find(' '); 更容易

    消除所有空格

    string foo = "thisIsThe         Test     Input";
    string bar[100];
    
    for (int i = 0; i < foo.length(); i++)
    {
        if (foo[i] != ' ')
            bar[i] = foo[i];
    
    
    }
    for (int i = 0; i < sizeof(bar) / sizeof(bar[i]); i++)
        cout << bar[i];
    

    每个词之间留一个空格:

    string foo = "thisIsThe         Test     Input";
        string bar[100];
    
        for (int i = 0; i < foo.length(); i++)
        {
            if (foo[i] != ' ')
                bar[i] = foo[i];
    
            else if (foo[i + 1] != ' ' && foo[i] == ' ')
                bar[i] = ' ';
    
        }
        for (int i = 0; i < sizeof(bar)/sizeof(bar[i]); i++)
    
    
    cout << bar[i];
    

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 2023-03-24
      • 2017-06-18
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多