2012-07-13 22 views
-5

可能重複:
Reaching a specific word in a string在一個字符串到達​​第3個字

我問了一個非常類似的問題,但顯然我問它錯了。現在的問題是,我需要在C++字符串達到第3個字和字符串是這樣的:

word1\tword2\tword3\tword4\tword5\tword6 

WORD2可以有內部空間。

我試圖讀取字符的字符串的字符,但我發現它效率低下。我試過代碼

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

並且由於word2中的空格而沒有工作。

你能告訴我,我該怎麼辦呢?

+2

那麼,你嘗試過這麼遠嗎?你必須嘗試一些東西。你卡在哪裏?你顯然知道什麼是分開的話。你是如何尋找這些的? – Bart 2012-07-13 12:25:32

+2

這是第三次或多或少地提出相同的問題......只是使用例如[這個答案](http://stackoverflow.com/a/11469613/214671)你已經收到!編輯:或者稍微修改一下[我上次爲你寫的代碼](http://stackoverflow.com/a/11362616/214671)。 – 2012-07-13 12:27:50

+0

你沒有向我們展示你所嘗試過的。給我們看一看。你卡在哪裏?看起來你解決了你以前的問題,這應該可以幫助你。 – Bart 2012-07-13 12:27:51

回答

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 
+0

非常感謝,這真的幫助.. – bahadirtr 2012-07-13 12:54:18

0

嘗試下面的例子。 您的第三個詞是std :: vector中的第3個項目...

創建一個拆分字符串函數,將大字符串拆分爲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; 
} 
相關問題