检查字符串是否包含子字符串,而不考虑大小写
Checking if a string contains a substring, regardless of capitalization
假设我有一个字符串str.
我要检查str是否包含关键字:"samples"然而,"samples"可以是任何形式的大写,例如:"samples"、"samples"、"samples"。
这就是我正在尝试的:
string str = "this is a FoO test";
if (str.find("foo") != std::string::npos){
std::cout << "WORKS";
}
这不会检测到"FoO"子字符串。有没有什么论点可以让我忽略资本化?或者我应该完全使用其他东西?
有多种选择。
使用boost::algorithm::ifind_first
首先包括<boost/algorithm/string/find.hpp>
和<string>
。
然后使用ifind_first
,如下所示。
std::string str = ...;
std::string subStr = ...;
boost::iterator_range<std::string::const_iterator> rng;
rng = boost::ifind_first(str, subStr);
使用char_traits
struct ci_char_traits : public char_traits<char>
{
static bool eq(char c1, char c2) { return toupper(c1) == toupper(c2); }
static bool ne(char c1, char c2) { return toupper(c1) != toupper(c2); }
static bool lt(char c1, char c2) { return toupper(c1) < toupper(c2); }
static int compare(const char* s1, const char* s2, size_t n)
{
while( n-- != 0 )
{
if( toupper(*s1) < toupper(*s2) ) return -1;
if( toupper(*s1) > toupper(*s2) ) return 1;
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s, int n, char a)
{
while(n-- > 0 && toupper(*s) != toupper(a))
{
++s;
}
return s;
}
};
typedef std::basic_string<char, ci_char_traits> ci_string;
然后您可以按如下方式使用它。
ci_string str = ...;
std::string subStr = ...;
auto pos = str.find(subStr.c_str());
请注意,这方面的问题是,在调用find函数、将ci_string分配给std::string或将std::字符串分配给ci_string时,需要使用c_str函数。
将std::search
与自定义谓词一起使用
正如文章中所建议的不区分大小写的std::string.find().
相关文章:
- 类中的字符串不命名类型
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 不考虑模板构造函数
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 为什么子项目 CMAKE 不考虑 fno-sanitize,请禁用目标的消毒器
- 反转字符串.不知道为什么这个逻辑是错误的.C++
- 如何保护非托管应用程序中的字符串不受进程转储的影响
- 修改向量中的字符串?(不使用循环)
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- C ++相同的字符串不相等(实际上是char*)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- CFileFind不考虑目录的第一个文件
- 初始化值是否保证通过其自己的地址反映,而不考虑内存顺序
- 将字符从一个字符串简单分配到另一个字符串不起作用
- 矢量重新分配,而不考虑储备
- GlobalMemoryStatusEx 不考虑新阵列
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 为什么字符串不会在堆栈中推送或弹出
- 检查字符串是否包含子字符串,而不考虑大小写