我想在比較字符串到「%」符號的C++中實現字符串比較。C++比較最多「%」符號的字符串char
我能做到這一點是這樣的:
std::equal(str1.begin(),
std::find(str1.begin(), str1.end(), L'%'),
str2.begin());
由於我在一個循環過許多字符串這樣做,我不知道是否有沒有兩個不同的字符串遍歷了find
和equal
的方法(可能與一個可以在任何時候中止比較的謂詞)。提升是好的。
我想在比較字符串到「%」符號的C++中實現字符串比較。C++比較最多「%」符號的字符串char
我能做到這一點是這樣的:
std::equal(str1.begin(),
std::find(str1.begin(), str1.end(), L'%'),
str2.begin());
由於我在一個循環過許多字符串這樣做,我不知道是否有沒有兩個不同的字符串遍歷了find
和equal
的方法(可能與一個可以在任何時候中止比較的謂詞)。提升是好的。
您可以試試std::mismatch
。
下面的代碼將運行在C++ 14(它需要的模板超載有兩個迭代器對),但它工作在C++ 11非常相似(或03,不lambda表達式雖然):
auto iters = std::mismatch(str1.begin(), str1.end(), str2.begin(), str2.end(),
[] (char lhs, char rhs) {return lhs != '%' && lhs == rhs;});
if (iters.first == str1.end()
|| iters.second == str2.end()
|| *iters.first == '%')
// Success […]
Demo 。
不錯不錯不錯! std :: mismatch在C++ 03中是一項獎勵。 – 2014-12-05 19:11:26
下面是做這件事的hackish的方式:
auto it = std::find_if(
str1.begin(), str1.end(),
[&str2](const char &c) {
return c == '%' || str2[&c - &str1[0]] != c
}
);
bool equal = (it == str1.end() || *it == '%');
的想法是創建一個謂語「字是一樣的,在其他的字符串,而不是一個'%'
」。
它依賴於str2
足夠長,但問題中的代碼也是如此。
你可以舉一些你正在比較的字符串的例子嗎?你的輸入字符串至少有3種不同的解釋。 – 2014-12-05 19:03:23
「當前音量爲:\」%1 \「」與「當前音量爲:\」C:\「」 – 2014-12-05 19:07:41
「str1」總是包含'%'或可以'str2'包含它但不包含'str1'? – greatwolf 2014-12-05 19:13:54