2017-02-26 4 views
0

私は割り当てを手掛けようとしています。アイデアは、文字列の配列とファイルストリームを取得することです。私はファイル内のそれらの文字列を探し、これらの文字列の出現を数える必要があります。fgetsとstrstrを使ってCの文字列を見つけて数えよう

私は基本的なループを持っていると思う。唯一の問題は、行中に文字列が見つかったときに、見つかった文字列が始まる位置から1から始まって、その文字列を再度検索したいということです(2回以上出現した場合)。

#define LINE_MAX_CHARS 1000 

// n = number of strings to be found 
// **strings = array of strings to look for in file 
void count_occurrences (int n, FILE *file, char **strings) { 
    char str[LINE_MAX_CHARS]; // buffer 
    int count = 0; 
    while (fgets(str, LINE_MAX_CHARS, file) != NULL){ // for each line 
     for (int i = 0; i < n; i++){ // for each word in line 
      char *found; 
      found = (strstr(str, (*(strings + i)))); // search line 
      if (found != NULL){ // if word found in line 
      // here, I want str (the buffer) to have its 0-th element to be the element at (found + 1), 
      // and the 1-st element to be (found + 2) and so on... 
      i--; // to look for same word in the rest of the line 
      count = count + 1; 
      } 
     } 
    } 
} 

もう1つの問題は、自分のコードをテストする方法がないことです。私はちょうど実行され、私のコードが正しい出力を生成しているかどうか私に教えるテストプログラムを与えられています。

私はfgetsとstrstrを使用する必要があります。

提案?

+2

'(*(strings + i))'してください。インデックスが作成されています。 – wildplasser

+0

@wildplasser私は、あなたが私を殴ってしまったと気づく前に、文字通りほぼ何かを書こうとしていました:P –

+0

私はCを初めて熟知しています。それは同じ出力、右を与える必要がありますか? –

答えて

1

strstr(str, strings[i])文字列内の位置へのポインタを返します。あなたはそのポインタ(str++)を増やすことができ、strstr()にループバックすることができるはずです。毎回カウントを増やして、strstr()NULLまたはstrがヌル文字に当たったらループを終了します。

これは次のようになります。私はこれをテストしていない。これはあなたの宿題なので、うまく動作しない/コンパイルできない場合は、デバッグするために残しておきます。それは、現在の行にstrings[i]のすべての発生をカウントするために...私はすべてあなたのために仕事をしていません

;-)

void count_occurrences (int n, FILE *file, char **strings) { 
    char str[LINE_MAX_CHARS]; 
    int count = 0; 

    while (fgets(str, LINE_MAX_CHARS, file) != NULL){ 
    for (int i = 0; i < n; i++){ 
     char *pos = str; 

     while(((pos = strstr(pos, strings[i]) != NULL) && *pos != '\n') { 
     count++; 
     pos++; 
     } 
    } 
    } 
} 
0

を意味し、あなたがループを使用する必要がありますし、あなたはstrstrに、最後に出現した後に少なくとも1つの位置を開始させる必要があります。次のコードを参照してください:

#define LINE_MAX_CHARS 1000 

// n = number of strings to be found 
// **strings = array of strings to look for in file 
void count_occurrences (int n, FILE *file, char **strings) { 
    char str[LINE_MAX_CHARS]; // buffer 
    int count = 0; 
    while (fgets(str, LINE_MAX_CHARS, file) != NULL){ // for each line 
     for (int i = 0; i < n; i++){ // for each word in line 
      char *found = str; 
      do { 
      found = strstr(found, strings[i]); // search line 
      if (found != NULL){ // if word found in line 
       count = count + 1; 
       found++; 
      } 
      } 
      while (found) 
     } 
    } 
} 
関連する問題