【问题标题】:Reaching the 3rd word in a string [duplicate]达到字符串中的第三个单词[重复]
【发布时间】:2012-07-13 12:23:05
【问题描述】:

可能重复:
Reaching a specific word in a string

我问了一个非常相似的问题,但显然我问错了。问题是我需要在 C++ 中达到字符串中的第三个单词,字符串是这样的:

word1\tword2\tword3\tword4\tword5\tword6

word2 里面可以有空格。

我试图逐个字符地读取字符串,但我发现它效率低下。我试过代码

std::istringstream str(array[i]); 
str >> temp >> temp >> word; 
array2[i] = word; 

由于 word2 中的空格,它不起作用。

你能告诉我怎么做吗?

【问题讨论】:

  • 那么,到目前为止,您尝试了什么?你一定尝试过什么。你在哪里卡住了?您显然知道单词之间的区别。您是如何搜索这些的?
  • 这是您第三次或多或少地问相同的问题......只需使用例如this answer你已经收到了!编辑:或稍作调整the code I wrote for you last time
  • 您并没有向我们展示您尝试过的内容。给我们看一看。你卡在哪里了。看来你已经解决了你之前的问题,这应该可以帮助你。
  • word2里面可以有空格吗? ..您至少应该向我们展示实际的字符串..
  • 我试图逐个字符地读取字符串,但我发现它效率低下。我试过code std::istringstream str(array[i]); str >> temp >> temp >> word; array2[i] = 单词;由于 word2 中的空格,它不起作用..

标签: c++ string word


【解决方案1】:

最直接的方法:

#include <iostream>
int main()
{
    //input string:
    std::string str = "w o r d 1\tw o r d2\tword3\tword4";
    int wordStartPosition = 0;//The start of each word in the string

    for( int i = 0; i < 2; i++ )//looking for the third one (start counting from 0)
        wordStartPosition = str.find_first_of( '\t', wordStartPosition + 1 );

    //Getting where our word ends:
    int wordEndPosition = str.find_first_of( '\t', wordStartPosition + 1 );
    //Getting the desired word and printing:
    std::string result =  str.substr( wordStartPosition + 1, str.length() - wordEndPosition - 1 );
    std::cout << result;
}

输出:

word3

【讨论】:

    【解决方案2】:

    试试下面的例子。 您的第三个词是 std::vector 中的第三项...

    创建一个拆分字符串函数,它将一个大字符串拆分为一个 std::vector 对象。使用该 std::vector 来获取您的第三个字符串。

    请看下面的例子,尝试在一个空的 C++ 控制台项目中运行。

    #include <stdio.h>
    #include <vector>
    #include <string>
    
    void splitString(std::string str, char token, std::vector<std::string> &words)
    {
        std::string word = "";
        for(int i=0; i<str.length(); i++)
        {
            if (str[i] == token)
            {
                if( word.length() == 0 )
                    continue;
    
                words.push_back(word);
                word = "";
                continue;
            }
    
            word.push_back( str[i] );
        }
    }
    
    
    int main(int argc, char **argv)
    {
        std::string stream = "word1\tword2\tword3\tword4\tword5\tword6";
    
        std::vector<std::string> theWords;
        splitString( stream, '\t', theWords);
    
        for(int i=0; i<theWords.size(); i++)
        {
            printf("%s\n", theWords[i].c_str() );
        }
    
        while(true){}
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多