2013-06-18 78 views
1

我的命令是:分割字符串選擇上空間

move 1 "South Africa" "Europe" 

代碼:

do 
{ 
    cut = text.find(' '); 
    if (cut == string::npos) 
    { 
    params.push_back(text); 
    } 
    else 
    { 
    params.push_back(text.substr(0, cut)); 
    text = text.substr(cut + 1); 
    } 
} 
while (cut != string::npos); 

的問題是,South Africa是越來越分成SouthAfrica,我需要它保持South Africa。切割後

參數:

1, South, Africa, Europe 

,我需要它是:

1, South Africa, Europe 

我怎樣才能做到這一點?用正則表達式?

的命令又如:

move 3 "New Island" "South Afrika" 

後'我的代碼切,我需要在PARAMS,我推回

3, New Island, South Africa 

我的代碼使:

3,"New,Island","South,Africa" 
+1

請粘貼更多完整的輸入示例,希望的輸出是什麼,最好是用一些更完整的代碼示例。 – Massa

+2

如果引號是在輸入中輸入的,那麼輸入是明確的,並且您可以通過發現「單詞」何時以雙引號開頭並查找第一個結束引用而不是第一個空格來準確解析。如果不包含引號,則輸入不明確,您必須提供一種方法(啓發式)來消除歧義,或重新設計可接受的引用以明確。請記住,您需要一種機制來處理嵌入式報價 - 至少在一般情況下。 –

+0

考慮使用流並使用'operator >>'來提取每個由空格分隔的單詞。 – andre

回答

1

您可以使用std::stringstreamstd::getline分析您的字符串

#include <iostream> 
#include <sstream> 
#include <string> 

int main() { 
    std::string text("move 3 \"New Island\" \"South Afrika\""); 
    std::string command, count, country1, country2, temp; 
    std::stringstream ss(text); 

    ss >> command >> count; 
    ss.str(""); 
    ss << text; 
    std::getline(ss, temp, '\"'); 
    std::getline(ss, country1, '\"'); 
    std::getline(ss, temp, '\"'); 
    std::getline(ss, country2, '\"'); 

    std::cout << command << ", " << count << ", " << 
     country1 << ", " << country2 << std::endl; 
    return 0; 
}