gpt4 book ai didi

C程序计算子串

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:46 25 4
gpt4 key购买 nike

为什么我的程序总是跳过最后的子串计数?

例如 1。字符串:dbdbsnasdb dbdxx

子字符串:db

计数:4 (没有错误)

例如2。字符串:dbdbsnasmfdb

子字符串:db

计数:2 (应该是 3 个)

** #include <stdio.h>只有

int countSubstr(char string[], char substring[]) {
int i, j;
int count = 0;
int subcount = 0;
for (i = 0; i <= strlen(string);) {
j = 0;
count = 0;
while ((string[i] == substring[j])) {
count++;
i++;
j++;
}
if (count == strlen(substring)) {
subcount++;
count = 0;
} else
i++;
}
return subcount;
}

为什么我必须申报我的 jcount成为0在for循环中?是因为j必须保留为 0 (子字符串保持不变)无论何时循环?

最佳答案

  1. 您的内部循环 (while) 可以继续比较两个字符串中的空终止符。您需要在其中一个字符串到达​​其终止空字符时立即停止它。
  2. 您的外循环条件存在差一错误。但无论如何您都不需要 strlen 调用。只是迭代直到空字符。
  3. 您还可以将 strlen(substring) 移到循环之外,以避免可能重新计算它。

更好的版本可能是这样的:

int countSubstr(char string[], char substring[])
{
int subcount = 0;
size_t sub_len = strlen(substring);
if (!sub_len) return 0;

for (size_t i = 0;string[i];) {
size_t j = 0;
size_t count = 0;
while (string[i] && string[j] && string[i] == substring[j]) {
count++;
i++;
j++;
}
if (count == sub_len) {
subcount++;
count = 0;
}
else {
i = i - j + 1; /* no match, so reset to the next index in 'string' */
}
}
return subcount;
}

关于C程序计算子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46242809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com