単語が見つかったかどうかを確認する必要があります。その場合は、グローバルカウンタをインクリメントします。それ以外の場合は、新しい単語を文字列のグローバル配列にコピーします。
のような何か:
#include <stdio.h>
#include <string.h>
// Global variables to hold the results
char word[80][81];
int count[80] = { 0 };
int extract_and_count(char *source,int *strings_cnt){
char token[80][81];
char *p;
int i = 0;
// Find all words in the input string
p = strtok(source, " ");
while(p != NULL){
strcpy(token[i],p);
// printf("%s\n",*(token+i));
i++;
p = strtok(NULL , " ");
}
// Find unique words and count the number a word is repeated
*strings_cnt = 0;
int j,k;
// Iterator over all words found in the input string
for(j = 0 ; j < i ; j++){
// Check if the word is already detected once
int found = 0;
for(k = 0 ; k < *strings_cnt ; k++){
if (strcmp(word[k], token[j]) == 0)
{
// The word already exists - increment count
found = 1;
count[k]++;
break;
}
}
if (!found)
{
// New word - copy it and set count to 1
strcpy(word[*strings_cnt], token[j]);
count[*strings_cnt] = 1;
(*strings_cnt)++;
}
}
return 1;
}
int main(void)
{
char s[] = "c language is difficult c is also fun";
int c, i;
printf("Searching: %s\n", s);
extract_and_count(s, &c);
printf("Found %d different words\n", c);
for (i=0; i<c; i++)
{
printf("%d times: %s\n", count[i], word[i]);
}
return 0;
}
出力:
Searching: c language is difficult c is also fun
Found 6 different words
2 times: c
1 times: language
2 times: is
1 times: difficult
1 times: also
1 times: fun
私はあなたのコードのスタイルに従うことを試みたが、私はこれらのコメントを追加したいと上:
1)あなた実際には配列token
は必要ありません。最初のループは、最終結果を直接更新するように変更することができます。
2)は、コードのような通常のセパレータを扱うことができない)
3グローバル変数を使用しないでください。 :など
4)単語とカウントを構造体に入れる必要があります。
コメント1,2および考慮に4を考慮すると、コードは次のようになります。
#include <stdio.h>
#include <string.h>
// Global variables to hold the results
struct WordStat
{
char word[81];
int count;
};
int extract_and_count(char *source,int *strings_cnt, struct WordStat* ws, int max){
char *p;
int i = 0;
int k;
*strings_cnt = 0;
// Find all words in the input string
p = strtok(source, " ");
while(p != NULL){
// Check if the word is already detected once
int found = 0;
for(k = 0 ; k < *strings_cnt ; k++){
if (strcmp(ws[k].word, p) == 0)
{
// The word already exists - increment count
found = 1;
ws[k].count++;
break;
}
}
if (!found)
{
// New word - copy it and set count to 1
strcpy(ws[*strings_cnt].word, p);
ws[*strings_cnt].count = 1;
(*strings_cnt)++;
}
i++;
p = strtok(NULL , " ");
}
return 1;
}
#define MAX_WORDS 80
int main(void)
{
struct WordStat ws[MAX_WORDS];
char s[] = "c language is difficult c is also fun";
int c, i;
printf("Searching: %s\n", s);
extract_and_count(s, &c, ws, MAX_WORDS);
printf("Found %d different words\n", c);
for (i=0; i<c; i++)
{
printf("%d times: %s\n", ws[i].count, ws[i].word);
}
return 0;
}
ここにコード – GMichael
を投稿してください私は、問題のいくつかのコードを入れて、それは良いものではなく、まったく動作しません。ちょうどスタートバージョンです。私はすべての単語を格納するために新しい配列を作成し、次にトークン[] []内の単語の値を数え、単語[] [] count []内の値。 –
私はまだあなたの目的を理解していません。また、「extract_and_count」の入力パラメータの意味、単語区切りの意味、配列内の単語の並び方を理解していません – GMichael