gpt4 book ai didi

c - 从字符数组中删除常用字母的程序

转载 作者:行者123 更新时间:2023-11-30 20:35:16 24 4
gpt4 key购买 nike

void main()
{
int i, j, k,flag=1;
char key[10], keyword[10];
gets(key);
i=0;
j=0;
while(key[i]!='\0') {
k=0;
while(keyword[k]!='\0') {
if(key[i]==keyword[k]) {
i++;
flag=0;
break;
}
k++;
}
if(flag==1) {
keyword[j]=key[i];
j++;
i++;
}
flag=1;
}
}

在这里,我尝试将唯一的字母表从数组复制到另一个数组..意味着重复的字母表不应复制到另一个数组中..它显示正确的输出,但同时它显示一些垃圾值,例如笑脸或其他值,直到原始长度为止输入数组(即key[])

最佳答案

您需要在初始化时以及每次添加新字母时为唯一字符串添加终止符both:

#include <stdio.h>

int main() {
int i = 0, j = 0;
char redundant[10], unique[10] = { '\0' };

gets(redundant);

while (redundant[i] != '\0') {
int k = 0, flag = 1;

while (unique[k] != '\0') {
if (redundant[i] == unique[k]) {
flag = 0;
break;
}
k++;
}

if (flag) {
unique[j++] = redundant[i];
unique[j] = '\0';
}

i++;
}

printf("%s -> %s\n", redundant, unique);

return(0);
}

输出

% ./a.out
warning: this program uses gets(), which is unsafe.
aardvark
aardvark -> ardvk
%

现在让我们考虑一种不同的方法,该方法浪费一些空间来简化和加速代码:

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

int main() {
unsigned char seen[1 << (sizeof(char) * 8)] = { 0 }; // a flag for every ASCII character
char redundant[32], unique[32];

(void) fgets(redundant, sizeof(redundant), stdin); // gets() is unsafe

redundant[strlen(redundant) - 1] = '\0'; // toss trailing newline due to fgets()

int k = 0; // unique character counter

for (int i = 0; redundant[i] != '\0'; i++) {
if (!seen[(size_t) redundant[i]]) {
unique[k++] = redundant[i];
seen[(size_t) redundant[i]] = 1; // mark this character as seen
}
}

unique[k] = '\0'; // terminate the new unique string properly

printf("%s -> %s\n", redundant, unique);

return 0;
}

我们使用一个标志数组( bool 值)(其中字母是索引)来确定该字母是否已被处理,而不是使用第二个内部循环来搜索字母是否已被复制。

您可能需要考虑的另一件事是是否以不同方式处理大小写或将它们合并为一个。

关于c - 从字符数组中删除常用字母的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924719/

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