C++ 不区分大小写的字符串::find
对于C++ 不区分大小写的字符串::find,c++,C++,对于std::string,是否存在不区分大小写的find()方法?对于(int i=0;i在做任何有趣的事情之前,请查看 for(int i=0; i<yourString.length() && tolower(yourString[i])!=yourLoweredChar; i++) { return i; } return -1; 并查看是否需要使用自定义字符特征类。您可以将两个字符串都大写,然后使用常规查找。(注意:如果使用Unicode字符
std::string
,是否存在不区分大小写的find()
方法?对于(int i=0;i在做任何有趣的事情之前,请查看
for(int i=0; i<yourString.length()
&& tolower(yourString[i])!=yourLoweredChar; i++)
{
return i;
}
return -1;
并查看是否需要使用自定义字符特征类。您可以将两个字符串都大写,然后使用常规查找。(注意:如果使用Unicode字符串,这种方法可能不正确。)
在Boost中还有用于不区分大小写搜索的ifind\u first
(注意,它返回的是一个范围,而不是size\u t
)
#包括
#包括
#包括
#包括
std::字符串大写(std::字符串输入){
for(std::string::iterator it=input.begin();it!=input.end();++it)
*it=toupper(*it);
返回输入;
}
int main(){
std::string foo=“1 foo 2 foo”;
std::string target=“foo”;
printf(“string.find:%zu\n”,foo.find(target));
printf(“string.find w/大写:%zu\n”,大写(foo).find(大写(目标));
printf(“ifind_first:%zu\n”,boost::algorithm::ifind_first(foo,target).begin()-foo.begin());
返回0;
}
这是我的建议(与@programmersbook相同)
#包括
#包括
#包括
布尔下限测试(字符l,字符r){
返回(std::tolower(l)=std::tolower(r));
}
int main()
{
std::字符串文本(“foo-BaR”);
std::字符串搜索(“bar”);
std::string::iterator fpos=std::search(text.begin(),text.end(),search.begin(),search.end(),lower_test);
如果(fpos!=text.end())
std::cout取决于“不区分大小写”的含义。您是只有ASCII字母,还是需要完整的Unicode排序?我刚给了ifind_一个测试驱动器,它比将两个字符串转换为小写(使用boost)和std::string::find慢。但在一般情况下,它对Unicode不起作用。“ß”和“SS”应该比较相等,但是Boost字符串算法不能处理这个问题。@ Dalle:在这种情况下,你应该使用Unicode库,比如 LIbIU
(在这些情况下,你可能需要一个区域来知道土耳其语)。是的,可能是。太糟糕了,C++标准库不知道Unicode。
#include <string>
#include <boost/algorithm/string/find.hpp>
#include <cstdio>
#include <cctype>
std::string upperCase(std::string input) {
for (std::string::iterator it = input.begin(); it != input.end(); ++ it)
*it = toupper(*it);
return input;
}
int main () {
std::string foo = "1 FoO 2 foo";
std::string target = "foo";
printf("string.find: %zu\n", foo.find(target));
printf("string.find w/ upperCase: %zu\n", upperCase(foo).find(upperCase(target)));
printf("ifind_first: %zu\n", boost::algorithm::ifind_first(foo, target).begin() - foo.begin());
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
bool lower_test (char l, char r) {
return (std::tolower(l) == std::tolower(r));
}
int main()
{
std::string text("foo BaR");
std::string search("bar");
std::string::iterator fpos = std::search(text.begin(), text.end(), search.begin(), search.end(), lower_test);
if (fpos != text.end())
std::cout << "found at: " << std::distance(text.begin(), fpos) << std::endl;
return 0;
}