2016-03-26 118 views
-1

我有這個字符串:System->ONDRASHEK: Nick aaasssddd není v žádné místnosti,我需要aaasssddd作爲字符串的輸出。每次輸出都不相同。所以它必須從兩個空格中獲得。我嘗試過substr或split,但我對C++的瞭解很少。兩個空格之間的輸出

我覺得這代碼:

#include <string> 
    #include <iostream> 

    int main() 
    { 
    const std::string str = "System->ONDRASHEK: Nick aaasssddd není v žádné  místnosti"; 

    size_t pos = str.find(" "); 
    if (pos == std::string::npos) 
    return -1; 

    pos = str.find(" ", pos + 1); 
    if (pos == std::string::npos) 
    return -1; 

    std::cout << str.substr(pos, std::string::npos); 
    } 

但是不,我需要什麼。

+0

我假設你的意思是你得到'尼克',而不是那個?然後,跳過一個空格,你就在那裏。如果還有其他問題,請詳細解釋。 –

回答

1

我假設你想要給定字符串的第三個單詞。

您已經找到第二個空格,但輸出是從第二個空格到字符串結尾的子字符串。

相反,您需要找到第三個空格,並在兩個空格之間輸出子字符串。

所以這裏是修改。

#include <string> 
#include <iostream> 

int main() 
{ 
    const std::string str = "System->ONDRASHEK: Nick aaasssddd není v žádné  místnosti"; 

    size_t pos = str.find(" "); 
    size_t start; 
    size_t end; 
    if (pos == std::string::npos) 
     return -1; 

    pos = str.find(" ", pos + 1); 
    if (pos == std::string::npos) 
     return -1; 

    start = pos + 1; 

    pos = str.find(" ", pos + 1); 
    if (pos == std::string::npos) 
     return -1; 

    end = pos; 

    std::cout << str.substr(start, end - start) << std::endl; 
} 
+0

這就是我所需要的。謝謝你。 – Ondrashek

0

請說明一下您的問題嗎?你需要2個空格之間的子串?如果我是真的,找到第一個空格,然後打印字符串,直到找到另一個空格。你可以使用該字符