2016-08-07 12 views
1

Cでコードする方法を学習しようとしていますが、入力配列から配列にユニークな文字を追加しようとしています。ユニークな配列に非常に簡単な方法で存在します。要素が存在しない場合にのみ、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 

どうすればいいですか?次のように

答えて

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] 

しかし、これはそれを行うための長い道のりがあります。

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"); 
+0

ありがとう:短い方法は、一度入力を歩くカウントをインクリメントし、カウントを歩くと、1の値の印刷インデックスがすることです!私はこれを試してきましたが、 "インデックスiを使って入力をやり直してください"という部分に困惑しています。どうすれば "入力i"を選択できますか? – Sina

+0

@Sina私は 'for(int i = 0; i!= input_size; i ++)if(input [i] == input [index])を意味しますcountSame ++; ' – dasblinkenlight

+0

ありがとう!出来た! – Sina

関連する問題