2013-02-01 61 views
0

我有一個如下所示的c代碼。
我想計算以分隔符分隔的文本中的單詞數量。
代碼編譯但停止。
是什麼問題。
這是我的代碼如下。c中的字數不起作用

#include <stdio.h> 
#include <string.h> 

int WordCount(char *text,char delimiter) 
{ 
    char *s; 
    int count = 0; 
    strcpy(s,text); 
    while(*s){ 
     if(*s==delimiter){ 
      count++; 
     } 
    } 
    return count; 
} 

int main(void) 
{ 
    char *line = "a,b,c,d,e"; 

    printf("%d\n",WordCount(line,',')); 
    return 0; 
} 
+2

你的arent遞增指針s到實際通過串移動這。我很確定你的WordCount例程可能是一個無限循環的情況。 – trumpetlicks

回答

5

你忘了增加指針s,因此你有一個無限循環,而不是複製字符串(你需要分配內存),只要讓它指向輸入即可。

int WordCount(char *text,char delimiter) 
{ 
    char *s = text; 
    int count = 0; 
    // strcpy(s,text); 
    while(*s){ 
     if(*s==delimiter){ 
      count++; 
     } 
     ++s; 
    } 
    return count; 
} 
2
char *s; 
int count = 0; 
strcpy(s,text); 

s是未初始化的指針不是陣列對象。

2

char *s; - 爲堆棧或堆中的s分配內存。

錯誤在你的程序

  • 所有變量必須同時宣佈將initalized。
  • 有效內存應分配/分配給指針變量。
  • 不確定循環,它始終檢查字符串的第一個字符。

修改代碼,如下圖所示

... 
char *s = NULL; 
int count = 0; 
s = text; 
while(*s); 
{ 
    if (*s == delimiter) 
    { 
     count++; 
    } 
    s++; 
} 
... 
+1

他需要做一個副本,爲什麼分配? – trumpetlicks

+0

更新了我的答案 – rashok

+0

因此,現在你總是用s ++更新s,如果s [count] ==分隔符,你基本上是雙重計數,因爲你增加了計數,然後用s [count] – trumpetlicks