我正在尝试学习如何在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
请问我该怎么做?
答案 0 :(得分:3)
您应该按如下方式重新编写程序的算法:
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");