gpt4 book ai didi

c - 仅当元素不存在时才向 C 数组添加一个元素

转载 作者:太空宇宙 更新时间:2023-11-04 01:53:27 24 4
gpt4 key购买 nike

我正在尝试学习如何用 C 编写代码,并且我正在尝试以一种非常简单的方式从输入数组向数组添加唯一字符,前提是该字符不存在于唯一数组中。

我真的很困惑,希望能得到一些帮助,帮助我正确地思考它。这是我的代码:

    /* get each character and how many times it shows up 
* to do this we need to store each unique char in a char array, and the count for each
* unique char in an int array */
char unique_chars[count];
for(int each = 0; each < count; ++each)
unique_chars[each] = '0';

/* count is the total number of chars stored in theinput array. */
int no_times = 0;

for(int each = 0; each < count; ++each)
{
if(theinput[each] != unique_chars[each])
unique_chars[each] = theinput[each];
if(theinput[each] == unique_chars[each])
continue;

for(int item = 0; item < count; ++item){
if(theinput[each] == unique_chars[item]){
++no_times;
}
}
printf("%c is in theinput array %d times.\n", theinput[each], no_times);
no_times = 0;
}
/* print all the values in the unique_chars array*/
printf("values in unique_chars are: \n");
for(int each = 0; each < count; ++each);
printf("\n");

return 0;

这是我尝试过的许多事情之一。它返回以下内容:

./uniquely
exsss
The characters typed in are: exsss
Number of characters are: 6
values in unique_chars are:
e x s s s

请问我该如何正确执行此操作?

最佳答案

您应该按如下方式修改程序的算法:

set count_unique to zero
for each index in the input
set count to zero
go through input to again using index i
if input[index] is the same as input[i]
count++
if count is 1 after the loop
unique_chars[count_unique++] = input[index]
for each index from zero to count_unique
print unique_chars[index]

然而,这是一条漫长的道路。简短的方法是遍历一次输入,递增计数,然后遍历计数,并打印 1 值的索引:

int counts[256];
for (int i = 0 ; i != count ; i++) {
counts[(unsigned)input[i]]++;
}
for (int i = 0 ; i != 256 ; i++) {
if (counts[i] == 1) {
printf("%c ", i);
}
}
printf("\n");

关于c - 仅当元素不存在时才向 C 数组添加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38819528/

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