【问题标题】:Checking for duplicate words in a string in C [duplicate]在C中检查字符串中的重复单词[重复]
【发布时间】:2021-05-22 07:31:55
【问题描述】:

我在 c 中编写了一个代码来搜索字符串中的重复单词,它只是将字符串中的每个单词附加到 2d 字符串数组中,但是对于行数和重复字符串,它返回 0,什么是代码有问题?

int main() {
  char str[50] = "C code find duplicate string";
  char str2d[10][50];

  int count = 0;
  int row = 0, column = 0;

  for (int i = 0; str[i] != '\0'; i++) {
    if (str[i] != '\0' || str[i] != ' ') {
      str2d[row][column] = str[i];
      column += 1;
    } else {
      str2d[row][column] = '\0';
      row += 1;
      column = 0;
    }
  }

  for (int x = 0; x <= row; x++) {
    for (int y = x + 1; y <= row; y++) {
      if (strcmp(str2d[x], str2d[y]) == 0 && (strcmp(str2d[y], "0") != 0)) {
        count += 1;
      }
    }
  }

  printf("%i %i", row, count);

  return 0;
}

【问题讨论】:

  • 建议:利用这个机会学习使用调试器。
  • 条件str[i] != '\0' || str[i] != ' ' 不会像您预期的那样工作。请了解 De Morgan's laws 用于否定布尔表达式。顺便说一句,str[i] != '\0' 在循环内将始终为真,因为这是由循环条件处理的。
  • 循环条件x &lt;= rowy &lt;= row 也会出错。它们会使循环超出范围。
  • 最后,strcmp(str2d[y], "0") 应该做什么?

标签: arrays c string


【解决方案1】:

您的代码中存在多个问题:

  • 二维数组可能太小:一个 50 字节的字符串中可能有多达 25 个字,如果您考虑使用空格序列嵌入空字,则可能更多。

  • 测试if (str[i] != '\0' || str[i] != ' ') 始终为真。

  • 字符串中的最后一个单词在二维数组中不是以空结尾的。

  • 如果字符串以空格结尾,则 str2d[row] 处的单词未初始化

  • 空格序列导致将空词存储到二维数组中。

  • 测试strcmp(str2d[y], "0") 毫无意义。这可能是忽略空词的失败尝试,可以使用strcmp(str2d[y], "") 进行测试。

这是修改后的版本:

#include <stdio.h>
#include <string.h>

int main() {
    char str[50] = "C code find duplicate string";
    char str2d[25][50];
    int count = 0, row = 0, column = 0;

    for (int i = 0;;) {
        // skip initial spaces
        while (str[i] == ' ')
            i++;
        if (str[i] == '\0')
            break;
        // copy characters up to the next space or the end of the string
        while (str[i] != ' ' && str[i] != '\0')
            str2d[row][column++] = str[i++];
        str2d[row][column] = '\0';
        row++;
    }

    for (int x = 0; x < row; x++) {
        for (int y = x + 1; y < row; y++) {
            if (strcmp(str2d[x], str2d[y]) == 0)
                count += 1;
        }
    }

    printf("%i %i\n", row, count);

    return 0;
}

【讨论】:

    【解决方案2】:

    问题是:

    1. if (str[i] != '\0' || str[i] != ' ') 应该是 if (str[i] != '\0' &amp;&amp; str[i] != ' ')。如果我没记错的话,使用逻辑或将阻止到达else 案例。

    2. if (strcmp(str2d[x], str2d[y]) == 0 &amp;&amp; (strcmp(str2d[y], "0") != 0)) 应该是 if (strcmp(str2d[x], str2d[y]) == 0)。否则,当单词为"0" 时,您的代码不会计算重复。

    3. 一个。为避免混淆,请使用printf("Number of rows = %d, Number of duplicates = %d\n", row+1, count); 之类的内容。由于 C 数组从索引 0 开始,这就是代码中的 row 包含的内容。但是行数是1。

      b.如果您现在还没有意识到,str 变量中没有重复项:char str[50] = "C code find duplicate string";。因此,您的代码返回正确的值 0。将其更改为 char str[50] = "C code find duplicate duplicate";(例如),您的代码将正确返回 1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2018-10-17
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多