Returning C newb here again. I am trying my hand at the exercises in K and R C and on my way to trying exercise 1-14, I am really stumped. My solution works but is not always correct, I am seeking help to refine what I have written, or if there is a better (easier-to-understand!) way! My script:
#include <stdio.h>
/* How many times a character appears in an array */
main()
{
int c;
int count = 0;
int uniquecount = 0;
char array[20];
array[0] = '\0';
while((c = getchar()) != EOF)
{
array[++count] = c;
}
/* for each element in array,
* check if array[each] in newarray.
* if array[each] in newarray
* break and start checking again.
* if array[each] not in newarray
* add array[each] to end of newarray*/
printf("count = %d\n", count);
array[count] = '\0';
char newarray[count];
newarray[0] = '\0';
for(int a = 0; a < count; ++a)
{
for(int b = 0; b <= a; ++b)
{
if(newarray[b] == array[a])
break;
if(newarray[b] != array[b])
{
newarray[b] = array[b];
++uniquecount;
}
}
}
printf("uniquecount = %d\n", uniquecount);
newarray[uniquecount + 1] = '\0';
printf("array => ");
for(int i = 0; i < count; ++i)
printf("\'%c\'", array[i]);
printf("\n");
printf("newarray => ");
for(int i = 0; i < uniquecount + 1; ++i)
{
if(newarray[i] != '\0')
printf("\'%c\'", newarray[i]);
}
printf("\n");
}
When I try some simple strings, it works and sometimes it doesnt:
./times_in_array
this is
count = 9
uniquecount = 5
array => '''t''h''i''s'' ''i''s'' '
newarray => 't''h''i''s'' '
./times_in_array
something comes
count = 16
uniquecount = 11
array => '''s''o''m''e''t''h''i''n''g'' ''c''o''m''e''s'
newarray => 's''o''m''e''t''h''i''n''g'' ''c'
./times_in_array
another goes
count = 13
uniquecount = 12
array => '''a''n''o''t''h''e''r'' ''g''o''e''s'
newarray => 'a''n''o''t''h''e''r'' ''g''o''e''s'
Please can someone guide me to where I am wrong? Thanks a lot!