在 C 中排序并删除字符串中的重复项

Sort and remove duplicates in a string in C

我的 "creating" 代码有问题,我刚开始上大学,我需要帮助解决这个问题:制作一个 C 程序,您可以在其中排序并删除字符串中的重复单词。

例如:

输入:土豆土豆苹果橙草莓橙

输出:苹果橘子土豆草莓

这是我到目前为止所了解的,它只排序,但不删除重复项:

#include <stdio.h>
#include <string.h>
int main()
{
  int i, j, k, space = 0;
  char str[100], words[50][100], cmp[50];

  printf("Enter the string  \n");
  scanf(" %[^\n]s", str);
  for (i = 0; i < strlen(str); i++)
  {
    if ((str[i] == ' ')||(str[i] == ', ')||(str[i] == '.'))
      space++;
  }
  for (i = 0, j = 0, k = 0;j < strlen(str);j++)
  {
    if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))
    {
      words[i][k] = '[=10=]';
      i++;
      k = 0;
    }else
      words[i][k++] = str[j];
  }

  for (i = 0;i < space;i++) //loop for sorting
  {
    for (j = i + 1;j <= space;j++)
    {
      if ((strcmp(words[i], words[j]) > 0))  //swapping strings
      {
        strcpy(cmp, words[i]);
        strcpy(words[i], words[j]);
        strcpy(words[j], cmp);
      }
    }
  }
  printf("After sorting string is \n");
  for (i = 0;i <= space;i++)
    printf("%s ", words[i]);

  return 0;
}

我还没有了解指针或函数,无法使用它们来执行此代码。

谢谢, 阿莫林.

您的代码应如下所示:

#include <stdio.h>
#include <string.h>
void main()
{
  int i, j = 0, k, l, n, space = 0,pos;
  char str[100], words[50][100], cmp[50];

  printf("Enter the string  \n");
  scanf(" %[^\n]s", str);
  for (i = 0; i < strlen(str); i++)
  {
    if ((str[i] == ' ')||(str[i] == ', ')||(str[i] == '.'))
      space++;
  }
  for (i = 0, j = 0, k = 0;j < strlen(str);j++)
  {
    if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))
    {
      words[i][k] = '[=10=]';
      i++;
      k = 0;
    }else
      words[i][k++] = str[j];
  }

  for (i = 0;i < space;i++) //loop for sorting
  {
    for (j = i + 1;j <= space;j++)
    {
      if ((strcmp(words[i], words[j]) > 0))  //swapping strings
      {
        strcpy(cmp, words[i]);
        strcpy(words[i], words[j]);
        strcpy(words[j], cmp);
      }
    }
  }
  printf("After sorting string is \n");
  for (i = 0;i <= space;i++)
    printf("%s ", words[i]);

  for (i = 0;i < space;i++) //loop for removing duplicate word
  {
      if ((strcmp(words[i], words[i+1]) == 0))  // finding duplicate word
      {
        pos=i+1; //Store the location of duplicate word
        for (j = pos;j < space;j++) //loop for deleting duplicate
          {
        strcpy(words[j], words[j+1]);
      }
         space--;
         i--;
    }
  }
  printf("\n After deleting duplicate string is \n");
  for (i = 0;i <= space;i++)
    printf("%s ", words[i]);  

  return 0;
}

这将删除输入字符串中的所有重复词。