【问题标题】:How to remove first word from a string?如何从字符串中删除第一个单词?
【发布时间】:2014-10-01 09:24:18
【问题描述】:

假设我有

string sentence{"Hello how are you."}

我希望字符串句子有“你好吗”而没有“你好”。我该怎么做呢。

我尝试做类似的事情:

stringstream ss(sentence);
ss>> string junkWord;//to get rid of first word

但是当我这样做时:

cout<<sentence;//still prints out "Hello how are you"

很明显stringstream 不会改变实际的字符串。我也尝试过使用strtok,但它不适用于string。

【问题讨论】:

  • 如何将字符串拆分为单词(通过 stringstream),然后读取除第一个单词之外的所有单词?
  • 这可能需要我使用一个while循环并制作动态的字符串数组。有更简单的方法吗?
  • 你只需要使用一个向量,没有循环。看看这个:stackoverflow.com/questions/236129/how-to-split-a-string-in-c
  • @MatthiasB try it
  • @DmitryLedentsov 是的,我注意到了。我想错了方向。需要的当然是 std::getline: ideone.com/IxZRAt 。并不是说我无论如何都会使用这种方法...

标签: c++ string stringstream strtok


【解决方案1】:

试试下面的

#include <iostream>
#include <string>

int main() 
{
    std::string sentence{"Hello how are you."};

    std::string::size_type n = 0;
    n = sentence.find_first_not_of( " \t", n );
    n = sentence.find_first_of( " \t", n );
    sentence.erase( 0,  sentence.find_first_not_of( " \t", n ) );

    std::cout << '\"' << sentence << "\"\n";

    return 0;
}

输出是

"how are you."

【讨论】:

    【解决方案2】:
    str=str.substr(str.find_first_of(" \t")+1);
    

    测试:

    string sentence="Hello how are you.";
    cout<<"Before:"<<sentence<<endl;
    sentence=sentence.substr(sentence.find_first_of(" \t")+1);
    cout<<"After:"<<sentence<<endl;
    

    执行:

    > ./a.out
    Before:Hello how are you.
    After:how are you.
    

    假设该行不以空格开头。在这种情况下,这不起作用。

    find_first_of("<list of characters>").
    

    在我们的例子中,字符列表是空格和制表符。这将搜索任何字符列表的第一次出现并返回一个迭代器。之后添加 +1 将位置移动一个字符。然后位置指向该行的第二个单词。 Substr(pos) 将获取从位置开始到字符串最后一个字符的子字符串。

    【讨论】:

    • 查看 Vlad 的回答,了解如何解释前导空格。
    • 谢谢维杰!!最终,每个人​​的回答似乎都恰到好处,我非常感谢大家的帮助。 Vijay 您的解决方案是最简单有效的,感谢您的帮助。你能快速解释一下吗:find_first_of(" ")+1 再次感谢!
    【解决方案3】:

    有无数种方法可以做到这一点。我想我会选择这个:

    #include <iostream>
    #include <string>
    
    int main() {
        std::string sentence{"Hello how are you."};
    
        // First, find the index for the first space:
        auto first_space = sentence.find(' ');
    
        // The part of the string we want to keep
        // starts at the index after the space:
        auto second_word = first_space + 1;
    
        // If you want to write it out directly, write the part of the string
        // that starts at the second word and lasts until the end of the string:
        std::cout.write(
            sentence.data() + second_word, sentence.length() - second_word);
        std::cout << std::endl;
    
        // Or, if you want a string object, make a copy from the start of the
        // second word. substr copies until the end of the string when you give
        // it only one argument, like here:
        std::string rest{sentence.substr(second_word)};
        std::cout << rest << std::endl;
    }
    

    当然,除非你有很好的理由不这样做,否则你应该检查first_space != std::string::npos,这意味着没有找到空间。为了清楚起见,我的示例代码中省略了检查:)

    【讨论】:

      【解决方案4】:

      您可以使用string::find() 来定位第一个空格。一旦你有了它的索引,然后从空间索引之后的索引到字符串末尾的索引中获取带有string::substr()的子字符串。

      【讨论】:

        【解决方案5】:

        例如,您可以获取剩余的子字符串

        string sentence{"Hello how are you."};
        stringstream ss{sentence};
        string junkWord;
        ss >> junkWord;
        cout<<sentence.substr(junkWord.length()+1); //string::substr
        

        不过,这也取决于你想进一步做什么

        【讨论】:

        • 我更愿意再次使用字符串语句变量,而不仅仅是打印剩余的字符串。我对 substr 不太熟悉,也不太清楚你在用 junkWord.length()+1 做什么。
        【解决方案6】:

        一个班轮:

        std::string subStr = sentence.substr(sentence.find_first_not_of(" \t\r\n", sentence.find_first_of(" \t\r\n", sentence.find_first_not_of(" \t\r\n"))));
        

        工作示例:

        #include <iostream>
        #include <string>
        
        void main()
        {
            std::string sentence{ "Hello how are you." };
        
            char whiteSpaces[] = " \t\r\n";
        
            std::string subStr = sentence.substr(sentence.find_first_not_of(whiteSpaces, sentence.find_first_of(whiteSpaces, sentence.find_first_not_of(whiteSpaces))));
        
            std::cout << subStr;
        
            std::cin.ignore();
        }
        

        【讨论】:

          【解决方案7】:

          以下是如何使用stringstream 提取垃圾词,同时忽略前后的任何空格(使用std::ws),然后通过强大的错误处理获取句子的其余部分......

          std::string sentence{"Hello how are you."};
          std::stringstream ss{sentence};
          std::string junkWord;
          if (ss >> junkWord >> std::ws && std::getline(ss, sentence, '\0'))
              std::cout << sentence << '\n';
          else
              std::cerr << "the sentence didn't contain ANY words at all\n";
          

          看到它正在运行on ideone here....

          【讨论】:

            【解决方案8】:
            #include <iostream>  // cout
            #include <string>   // string
            #include <sstream> // string stream
            using namespace std;
            
            int main()
            {
                 string testString = "Hello how are you.";
            
                 istringstream iss(testString); // note istringstream NOT sstringstream
            
                 char c; // this will read the delima (space in this case)
                 string firstWord;
            
                 iss>>firstWord>>c; // read the first word and end after the first ' '
            
                cout << "The first word in \"" << testString << "\" is \"" << firstWord << "\""<<endl;
            
                cout << "The rest of the words is \"" <<testString.substr(firstWord.length()+1) << "\""<<endl;
                return 0;
            }
            

            输出

            “你好,你好吗”中的第一个词。是“你好” 剩下的词是“你好吗”。

            live testing at ideon

            【讨论】:

              猜你喜欢
              • 2011-10-12
              • 2022-01-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-07-17
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多