将字符串存储在要在 IF 语句中使用的数组中的可能方法
Possible way to store a string in an array to be used in an IF statement
我有以下代码,它搜索任何没有 Q 后跟 U 的单词。有什么可能的方法可以处理这段代码,让它只使用一个 if 语句,但搜索每个组合?
if (word1.find("qq") != std::string::npos) {
cout << word1 << endl;
}
if (word1.find("qa") != std::string::npos) {
cout << word1 << endl;
}
//...
这样做的限制是我认为它不会捕获"quqa"。
if (word1.find('q') != std::string::npos
&& word1.find("qu") == std::string::npos)
cout << word1 << endl;
编辑:这将计算"Q"的数量,并确保"qu"的数量相同。 我认为这可能比搜索每个文字组合更有效。
size_t stringCount(const std::string& referenceString,
const std::string& subString) {
const size_t step = subString.size();
size_t count(0);
size_t pos(0) ;
while( (pos=referenceString.find(subString, pos)) !=std::string::npos) {
pos +=step;
++count ;
}
return count;
}
bool check_qu(const std::string &word1)
{
int num_q = stringCount(word1, "q");
return (num_q > 0) ?
(stringCount(word1, "qu") == num_q) : true;
}
这个怎么样?
const char *string_list[] = {
"qq",
"qa",
"qz",
...
};
for (int i = 0; i < sizeof(string_list)/sizeof(*string_list); i++) {
if (word1.find(string_list[i]) != std::string::npos) {
cout << word1 << endl
}
我会将所有搜索字符串存储在一个容器中,然后循环访问它:
#include <vector>
#include <iostream>
int main(int, char**) {
std::string word1 = "this is the string to search";
std::vector<std::string> patterns;
patterns.push_back("qq");
patterns.push_back("qa");
// etc.
std::vector<std::string>::size_type i; // for better readability
for (i = 0; i < patterns.size(); i++) {
if (word1.find(patterns[i]) != std::string::npos) {
std::cout << word1 << std::endl;
}
}
}
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13