-5

可能重复:
到达字符串中的特定单词

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

word1\tword2\tword3\tword4\tword5\tword6

word2 里面可以有空格。

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

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

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

你能告诉我我该怎么做吗?

4

2 回答 2

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
于 2012-07-13T12:39:22.610 回答
0

试试下面的例子。您的第三个单词是 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;
}
于 2012-07-13T12:39:36.207 回答