2017-03-17 30 views
1

之間,我有一個是這樣的字符串:解析字符串支架

Room -> Subdiv("X", 0.5, 0.5) { sleep | work } : 0.5 

我需要以某種方式提取{}之間的2串,即sleepwork。格式嚴格,括號內只能有2個單詞,但單詞可以改變。括號前後的文字也可以更改。我這樣做的最初方式是:

string split = line.substr(line.find("Subdiv(") + _count_of_fchars); 
split = split.substr(4, axis.find(") { ")); 
split = split.erase(split.length() - _count_of_chars); 

但是,我意識到,這是不打算如果側弦括號改變Ø任何長度不同的工作。

這怎麼辦?謝謝!

+3

尋找'{'。尋找'|'。尋找'}'。在'{... |'之間進行子範圍,在'| ...}'之間進行子範圍。 –

+0

@VittorioRomeo好主意!我更少的C++詞彙真的是一個瓶頸!謝謝! –

+1

'{'和'}'之間只能有兩個單詞嗎?或者單詞的數量可以變化嗎? – muXXmit2X

回答

2

喜歡的東西:

unsigned open = str.find("{ ") + 2; 
unsigned separator = str.find(" | "); 
unsigned close = str.find(" }") - 2; 
string strNew1 = str.substr (open, separator - open); 
string strNew2 = str.substr (separator + 3, close - separator); 
1

沒有硬編碼任何數字:

  • 查找A作爲第一"{"從字符串的結尾索引,向後搜索。
  • 查找B作爲從"{"的位置開始向前搜索的第一個"|"的索引。
  • 查找C作爲從"|"的位置開始向前搜索的第一個"}"的索引。

BA之間的子串爲您提供第一個字符串。而CB之間的子串則爲您提供了第一個字符串。你可以在你的子字符串搜索中包含這些空格,或者稍後將它們取出。

std::pair<std::string, std::string> SplitMyCustomString(const std::string& str){ 
    auto first = str.find_last_of('{'); 
    if(first == std::string::npos) return {}; 

    auto mid = str.find_first_of('|', first); 
    if(mid == std::string::npos) return {}; 

    auto last = str.find_first_of('}', mid); 
    if(last == std::string::npos) return {}; 

    return { str.substr(first+1, mid-first-1), str.substr(mid+1, last-mid-1) }; 
} 

修剪的空間:

std::string Trim(const std::string& str){ 
    auto first = str.find_first_not_of(' '); 
    if(first == std::string::npos) first = 0; 

    auto last = str.find_last_not_of(' '); 
    if(last == std::string::npos) last = str.size(); 

    return str.substr(first, last-first+1); 
} 

Demo

1

即使你說的話找的量是固定的我使用正則表達式做了一個更靈活一點的例子。但是,使用Мотяs的答案仍然可以達到相同的結果。

std::string s = ("Room -> Subdiv(\"X\", 0.5, 0.5) { sleep | work } : 0.5") 
std::regex rgx("\\{((?:\\s*\\w*\\s*\\|?)+)\\}"); 
std::smatch match; 

if (std::regex_search(s, match, rgx) && match.size() == 2) { 
    // match[1] now contains "sleep | work" 
    std::istringstream iss(match[1]); 
    std::string token; 
    while (std::getline(iss, token, '|')) { 
     std::cout << trim(token) << std::endl; 
    } 
} 

trim除去開頭和結尾的空格,輸入字符串將可以很容易地擴展到這個樣子:"...{ sleep | work | eat }..."

Here是完整的代碼。