2017-06-20 47 views
-4

假設我有一個字符串,如下面充分利用主串詞或子字符串時從RHS字符「」被發現,然後刪除其餘

輸入=「\\路徑\ MYFILES這是我的刺「

輸出=MYFILES

從RHS時第一個字符 '\' 被發現得到詞(即MYFILES)並清除其餘部分。

下面是我的方法我累了,但它的壞,因爲有一個運行時錯誤,因爲終止與一個核心。

請建議最簡潔和/或最短的方式從上面的字符串中只獲得一個單詞(即MYFILES)?

我已經搜索並嘗試從過去兩天,但沒有運氣。請幫助

注:在上面的例子中,輸入字符串沒有硬編碼爲它應該是.The字符串包含動態的變化,但字符「\ '可以肯定。

std::regex const r{R"~(.*[^\\]\\([^\\])+).*)~"} ; 
std::string s(R"(" //PATH//MYFILES  This is my sting ")); 
std::smatch m; 
int main() 
{ 

if(std::regex_match(s,m,r)) 
{ 
std::cout<<m[1]<<endl; 

} 
} 
} 
+1

真的沒有理由在這裏使用正則表達式。你可以使用'find_last_of'和'find'結合'substr'來相當容易地得到這個單詞。 – NathanOliver

+0

謝謝你的回覆,你可以請小示例 – user7953556

+1

我記得一個問題*非常類似於今天早上發佈的這個問題。它包含了一些有用的建議,但它似乎已被刪除... –

回答

0

要清除字符串的部分,必須找到該部分的起始和結束位置。在std::string內部找到一些事件是非常容易的,因爲這個類有6個插入方法(std::string::find_first_of,std::string::find_last_of等)。這裏是你的問題,如何可以解決一個小例子:

#include <iostream> 
#include <string> 

int main() { 
    std::string input { " \\PATH\\MYFILES This is my sting " }; 
    auto pos = input.find_last_of('\\');  

    if(pos != std::string::npos) { 
     input.erase(0, pos + 1); 

     pos = input.find_first_of(' '); 
     if(pos != std::string::npos) 
      input.erase(pos); 
    } 

    std::cout << input << std::endl; 
} 

注:注意escape sequences,一個反斜槓被寫成"\\"一個字符串內。

相關問題