有没有比 char* 和循环更好的方法来计算字符串中的子字符串出现次数
Is there a better way to count substring occurrences within a string than char* and a loop?
我有这一行:
const char *S1 = "AaA BbB CcC DdD AaA";
我认为这会创建一个指针*S1
,它位于一个常量 char 类型值,并且其中包含 AaA BbB CcC DdD AaA
值。是吗?
如果是这样,如何读取此常量值的每个字符并识别AaA
发生多少次?
我正在考虑创建一个循环,将每个字母复制到不同的单元格,然后 3 个包含的 if
语句,其中第一个可以检查A
,第二个可以检查a
,依此类推。如果这 3 个是真的,我将像这样增加一个计数器i++
.这是对的吗?
我认为这太复杂了,可以用更少的代码来完成。
你的基本方法是合理的。但是,它很复杂且无法扩展:如果您想搜索三个以上字母的单词怎么办?四个if
?五if
?六。。。?显然这是行不通的。
相反,请使用两个循环:一个遍历您搜索的字符串("haystack"或"引用"(,另一个遍历您搜索的字符串("针"或"模式"(。
但幸运的是,您甚至不必这样做,因为C++为您提供了在另一个字符串中搜索一个字符串出现的工具,即find
函数:
#include <string>
#include <iostream>
int main() {
std::string const reference = "AaA BbB CcC DdD AaA";
std::string const pattern = "AaA";
std::string::size_type previous = 0;
int occurrences = 0;
for (;;) {
auto position = reference.find(pattern, previous);
if (position == std::string::npos)
break;
previous = position + 1;
++occurrences;
}
std::cout << occurrences << " occurrences of " << pattern << 'n';
}
您可以在C++参考中查找各个类型和函数。例如,您可以在那里找到std::string::find
功能,该功能为我们进行实际搜索。
请注意,这将找到嵌套模式:引用"AaAaA"将包含两次出现的"AaA"。如果这不是您想要的,请更改重新分配previous
位置的行。
实现所需目标的一种简单方法是使用 strstr(str1, str2)
函数,该函数返回指向 str1 中第一次出现的 str2 的指针,如果 str2 不是 str1 的一部分,则返回一个空指针。
int count_sequence(const char *S1, const char *sequence) {
int times, sequence_len;
const char *ptr;
times = 0;
sequence_len = strlen(sequence);
ptr = strstr(S1, sequence); //Search for the first sequence
while(ptr != NULL) {
times++;
ptr = strstr(ptr + sequence_len, sequence); //search from the last position
}
return times;
}
C++方式:
- 使用
std::string
进行字符串管理,它提供了很多好处,内存管理,迭代器,一些算法,如find
。 - 如果
s2
s1
中不存在,则使用find
std::string
方法搜索s2
开始的s1
索引(返回虚拟值 std::string::NPOS(。
法典:
#include <iostream>
int main() {
std::string s1("AaAaAaA");
//std::string s1("AaA BbB CcC DdD AaA");
std::string s2("AaA");
int times = 0;
size_t index = s1.find(s2, index);
while (index != std::string::npos) {
times++;
index = s1.find(s2, index + 1);
}
std::cout << "Found '" << s2 << "' in '" << s1 << "' "
<< times << " times" << std::endl;
}
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- 如何计算特定字母在字符串中出现的次数?(C++)
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 使用标准库计算字符串中的十进制数
- 如何计算字符串中用户输入元素的出现次数?
- 如何在 C++ 中计算字符串的算术运算
- 计算字符串中子字符串的出现次数
- 用于计算字符串中元音的函数
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 计算表达式字符串由 std::map 中的键组成
- 如何计算字符串 c++ 中的"xxx"数?
- 通过将文本文件读取为字符串/向量来计算加权/未加权 GPA
- 如何更有效地计算n个字符串之间的不匹配分数?
- 将字符串计算为 C++ 中的表达式
- 在C++中从字符串计算算术表达式
- 在字符串计算后添加空字符
- C++使用C字符串计算文件中的字符、单词、句子
- 不使用字符串计算数字中的数字