【问题标题】:C Program to count substringsC程序计算子串
【发布时间】:2017-09-15 15:18:14
【问题描述】:

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

例如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;
}

为什么我必须在 for 循环中声明我的 j 和 count 为 0?是因为j 在循环时必须保持为0(子字符串保持不变)?

【问题讨论】:

  • 在第二个示例中,尾随的空字符也匹配,使计数比子字符串长度高一。但是这段代码很糟糕,你走在最后——不要那样做。并将strlen 调用移出循环。
  • 可能else i++; 已超过增量。
  • 我应该如何更改我的代码?
  • 请注意,在 PHP 中这样的循环中 使用 strlen() 是可以的,但了解c-strings 你永远不会这样做。相反,您将检查 '\0' 终止符,如果您知道它,那么 while ((string[i] == substring[j])) 对您来说也会看起来不对。
  • string:ddd 和 substring:dd 的预期结果是什么? 2 或 1?

标签: c string substring


【解决方案1】:
  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;
}

【讨论】:

  • 1) )){ --> ){ 2) countSubstr("ddb", "db") 的结果是0。
  • while (string[i] 是多余的,只测试string[j] 就足够了。
  • 空子字符串的情况处理方式不同:countSubstr("", "") 应该返回 1,但是你的代码有一个无限循环
  • 空子串的处理方式不同:countSubstr("", "") 可能应该返回 1,但您的代码返回 0 并且对于 countSubstr("a", "") 有一个无限循环
  • 代码无法编译,即使经过轻度编辑,countSubstr("ddb", "db") 仍然是 0。次要:count = 0; --> size_t count = 0;
【解决方案2】:

您的代码中存在一些问题:

  • 循环for (i = 0; i &lt;= strlen(string);) 会在每次循环迭代时重新计算字符串的长度,而您迭代的次数过多。你应该写:for (i = 0; string[i] != '\0';)

  • 第二个循环可能会超出string 的末尾,并产生一个非常大的count 值:对于第二个示例,它将产生至少3,因为空终止符被计入所有情况。这解释了为什么您得到的匹配计数不正确。当您阅读超出两个字符串的末尾时,该行为实际上是未定义的。

这是一个更正的版本:

int countSubstr(char string[], char substring[]) {
    int len = strlen(string);
    int sublen = strlen(substring);
    int i, j, count = 0;
    for (i = 0; i <= len - sublen; i++) {
        for (j = 0; j < sublen && string[i + j] == substring[j]; j++)
            continue;
        if (j == sublen)
            count++;
    }
    return count;
}

请注意,任何给定字符串中空字符串的出现次数都将是字符串长度的 1 加,这是有道理的。

另请注意,此代码为 countSubstr("bbb", "bb") 返回 2,这可能与您的预期不同。接受的答案返回 1,这是有争议的。

【讨论】:

  • 这个程序的要求不允许我使用string.h
  • 另外(我认为这还不清楚)来自 cmets:string:ddd 和 substring:dd 的预期结果是什么? 2 还是 1? ... 应该是 1 我猜? – BEX 你的代码返回2。
  • @BLUEPIXY:我修改了答案以澄清这一点。 我猜应该是 1 几乎不符合规范 ;-)
  • 就我而言,countSubstr("bbb", "bb") = 1 是不正确的。我认为这个答案比公认的答案更好,但我个人不喜欢循环中断
【解决方案3】:

这适用于我测试的所有边缘情况

#include <stdio.h>

int countSubstr(char string[], char substring[])
{
    int count = 0;
    size_t i = 0;
    while(string[i])
    {
        int match = 1;
        size_t j = 0;
        while (substring[j])
        {
            match &= substring[j] == string[i + j];
            j++;
        }
        count += match;
        i++;
    }
    return count;
}

这里有一些测试用例:

void test(char name[], int expected, char string[], char substring[]){
    int actual = countSubstr(string, substring);
    char* status = (actual == expected)? "PASS" : "FAIL";
    printf("%s: %s\nActual: %d\nExpected: %d\n\n",name,status,actual,expected);
}

int main(void) {
    test("Two empty strings", 0, "", "");
    test("Empty substring", 19, "sub str sub str sub", "");
    test("Empty string", 0, "", "sub");
    test("Case 1", 4, "dbdbsnasdb dbdxx", "db");
    test("Case 2", 3, "dbdbsnasmfdb", "db");
    test("No match", 0, "dbdbsnasmfdb", "dxb");
    test("Inner matching", 3, "abababa", "aba");
    test("Identity test", 1, "a", "a");
    return 0;
}

【讨论】:

  • 良好的测试。最好使用size_t i,j; 来很好地处理长字符串,不像int i,j;
【解决方案4】:

在您的 while 循环中,您没有检查是否超过了字符串长度。

编辑:
请记住,在 C 中,所有字符串的末尾都有一个 '\0',但在您的 while 循环中,您不会检查它。

在您的特定示例中,我们得到(从最后一个 db 开始):
i = 10, j = 0, count = 1 (check for 'd')
i = 11, j = 1, count = 2 (check for 'b')
i = 12, j = 2, count = 3 (check for '\0')
i = 13, j = 3, count = 3 (exit loop)

count = 3 不同于 strlen(substring) == 2
-> 子计数没有增加

【讨论】:

    【解决方案5】:

    for (i = 0; i

    必须

    for (i = 0; i

    使用两个 for 代替一个非常复杂的循环,因为它更容易调试。

    【讨论】:

      猜你喜欢
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      相关资源
      最近更新 更多