我遇到了“创建”代码的问题,我刚刚开始上大学,我需要帮助解决这个问题:制作一个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] = '\0';
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;
}
我仍然没有学习指针或函数,也无法使用它们来执行此代码。
谢谢你, 阿莫林。
答案 0 :(得分: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] = '\0';
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;
}
这将删除输入字符串中的任何重复字词。