gpt4 book ai didi

c - 从 C 数组中删除重复的单词/字符串

转载 作者:行者123 更新时间:2023-11-30 16:54:38 25 4
gpt4 key购买 nike

我目前在代码输出方面遇到问题。它正确填充数组,但我删除重复单词时出现问题。

逐字填充数组:

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

int main(void) {
char str[610] = "C (pronounced like the letter C) is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. Although Cwas designed for implementing system software, it is also widely used for developing portable application software. C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which began as an extension to C.";
char tokChars[9]=" ;().,\n";
char *cptr;
int size = 100;
char array[1000][20];
char ob[1000][20];
int count;
int i= 0;
cptr = strtok(str, tokChars);
count = 1;

while(cptr != NULL)
{
strcpy(array[i], cptr);
printf("\n%s\n",array[i]);
printf("token %d --> %s \n",count , cptr);
cptr = strtok(NULL, tokChars);
count++;
i++;
}

要删除重复的单词:

int k = 0, r = 0,h = 0;
for(r= 0 ; r<100 ; r++)
{
while ( k< 100)
{
int a;
a = strcmp(array[r], ob[k]);
if (a != 0)
{
strcpy(ob[h],array[r]);
h++;

break;
}


k++;
}
}

int m = 0;
for(m= 0; m<size; m ++)
{
printf("\n%s\n",ob[m]);
}
return EXIT_SUCCESS;
}

显然输出打印出了数组中的每个单词。我应该改变什么?或者我误解的东西

最佳答案

以下应该有效:

int k, r, h;

strcpy(ob[0],array[0]); h= 1;
for(r= 0 ; r<100 ; r++)
{
k= 0;
while (k< h)
{
if (strcmp(array[r], ob[k]) == 0)
break;
k++;
}
if (k==h) {
strcpy(ob[h],array[r]);
h++;
}
}

主要问题是您将 array 的下一个元素与 ob(输出数组)的一个元素进行比较,如果 ob 中没有一个比较相等。然后您可以将此元素添加到 ob 并继续。

关于c - 从 C 数组中删除重复的单词/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40492641/

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