2013-03-19 41 views
2

有沒有辦法做到在一個單一的命令如下(爲避免測試)兩次一次字符串算法?

if (mystring.find_first_not_of("X") != std::string::npos) { 
    mystring.erase(0, mystring.find_first_not_of("X")); 
} 
+4

可以存儲結果變量中的'find_first_not_of'。你仍然需要做測試,但這將是一個超級便宜,持續時間的操作。 – zneak 2013-03-19 19:45:28

+0

你也許可以用'std :: find'和一個比較器。編輯:就像我按下輸入... – 2013-03-19 19:45:59

+0

此外,我感覺這裏的XY問題。您的代碼會刪除前導的'0'字符。你想分析或縮短整數字符串?因爲你不必去除前導的'0'字符。 – zneak 2013-03-19 19:50:30

回答

1
mystring.erase(0, std::max(0, (std::make_signed<std::string::size_type>::type) 
          mystring.find_first_not_of('X'))); 

或者沒有C++ 11:

mystring.erase(0, std::max(0, (int)mystring.find_first_not_of('X'))); 
+0

這實際上可能工作... – 2013-03-19 20:12:11

相關問題