2012-10-02 64 views
5

我需要編寫一個函數來計算字符串中的字。對於此作業的 目的,「字」被定義爲非空,非空白字符的序列 ,與其他字由 空格分隔。計算字符串中的字 - c編程

這是我到目前爲止有:

int words(const char sentence[ ]); 

int i, length=0, count=0, last=0; 
length= strlen(sentence); 

for (i=0, i<length, i++) 
if (sentence[i] != ' ') 
    if (last=0) 
     count++; 
    else 
     last=1; 
else 
    last=0; 

return count; 

我不知道是否可行與否,因爲直到我的整個程序完成我無法測試它,我不知道它會工作,有沒有更好的寫這個函數的方法?

+1

的功課標籤(已廢棄)(http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated)。請不要使用它。至於你的問題,我的第一個想法是'strtok',因爲分離事物就是它的意圖。無論如何,'if(sentence [i]> ='!'&& sentence [i]> ='〜')'除了僅僅依賴ASCII被使用之外還有點不正確。 – chris

+0

'!'和'〜'有什麼意義? *一切*什麼不是空白是一個單詞的一部分。 –

+0

謝謝,所以我將它改爲!='' – PhillToronto

回答

6

您需要

int words(const char sentence[]) 
{ 
} 

(注意括號)。

For循環與;而不是,


沒有任何聲明,這裏就是我會寫:

觀摩http://ideone.com/uNgPL

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

int words(const char sentence[ ]) 
{ 
    int counted = 0; // result 

    // state: 
    const char* it = sentence; 
    int inword = 0; 

    do switch(*it) { 
     case '\0': 
     case ' ': case '\t': case '\n': case '\r': // TODO others? 
      if (inword) { inword = 0; counted++; } 
      break; 
     default: inword = 1; 
    } while(*it++); 

    return counted; 
} 

int main(int argc, const char *argv[]) 
{ 
    printf("%d\n", words("")); 
    printf("%d\n", words("\t")); 
    printf("%d\n", words(" a  castle  ")); 
    printf("%d\n", words("my world is a castle")); 
} 
3

看下面的例子,你可以按照下面的方法:計算單詞之間的空白。

int words(const char *sentence) 
{ 
    int count=0,i,len; 
    char lastC; 
    len=strlen(sentence); 
    if(len > 0) 
    { 
     lastC = sentence[0]; 
    } 
    for(i=0; i<=len; i++) 
    { 
     if((sentence[i]==' ' || sentence[i]=='\0') && lastC != ' ') 
     { 
      count++; 
     } 
     lastC = sentence[i]; 
    } 
    return count; 
} 

測試:

int main() 
{ 
    char str[30] = "a posse ad esse"; 
    printf("Words = %i\n", words(str)); 
} 

輸出:

Words = 4 
+0

嘿@aleroot謝謝你。問題是,如果在句子開頭有一個空格,它會計數5 – PhillToronto

+0

@PhillToronto看到我現在修復的答案的更新,我知道它並不完美,但它可能是一個很好的起點。 .. – aleroot

+0

@aleroot「count」應該初始化爲零。您當前的代碼給出錯誤,因爲計數未用零初始化,因此無法遞增計數。 – furqan

2
#include <ctype.h> // isspace() 

int 
nwords(const char *s) { 
    if (!s) return -1; 

    int n = 0; 
    int inword = 0; 
    for (; *s; ++s) { 
    if (!isspace(*s)) { 
     if (inword == 0) { // begin word 
     inword = 1; 
     ++n; 
     } 
    } 
    else if (inword) { // end word 
     inword = 0; 
    } 
    } 
    return n; 
} 
0

這裏是另一種解決方案:

#include <string.h> 

int words(const char *s) 
{ 
    const char *sep = " \t\n\r\v\f"; 
    int word = 0; 
    size_t len; 

    s += strspn(s, sep); 

    while ((len = strcspn(s, sep)) > 0) { 
     ++word; 
     s += len; 
     s += strspn(s, sep); 
    } 
    return word; 
} 
-1

這是一個解決方案。即使詞語之間有多個空格,詞尾符號之間沒有空格,也可以正確計數單詞,例如:我是,我的母親是。大象,飛走。

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


int countWords(char*); 


int main() { 
    char string[1000]; 
    int wordsNum; 

    printf("Unesi nisku: "); 
    gets(string); /*dont use this function lightly*/ 

    wordsNum = countWords(string); 

    printf("Broj reci: %d\n", wordsNum); 

    return EXIT_SUCCESS; 
} 


int countWords(char string[]) { 
    int inWord = 0, 
     n, 
     i, 
     nOfWords = 0; 

    n = strlen(string); 

    for (i = 0; i <= n; i++) { 
     if (isalnum(string[i])) 
      inWord = 1; 
     else 
      if (inWord) { 
       inWord = 0; 
       nOfWords++; 
      } 
    } 

    return nOfWords; 
} 
+0

「不要輕易使用此功能」?你可能意思是「根本不使用這個功能」。 –

0
#include<stdio.h> 

int main() 
{  
char str[50];  
int i, count=1; 
printf("Enter a string:\n");  
gets(str);  
for (i=0; str[i]!='\0'; i++) 
     { 
     if(str[i]==' ')  
       { 
       count++; 
       } 
     } 
printf("%i\n",count);  
} 
2
bool isWhiteSpace(char c) 
{ 
    if(c == ' ' || c == '\t' || c == '\n') 
     return true; 
    return false; 
} 

int wordCount(char *string) 
{ 
    char *s = string; 
    bool inWord = false; 
    int i = 0; 

    while(*s) 
    { 
     if(isWhiteSpace(*s)) 
     { 
      inWord = false; 
      while(isWhiteSpace(*s)) 
       s++; 
     } 
     else 
     { 
      if(!inWord) 
      { 
       inWord = true; 
       i++; 
      } 
      s++; 
     } 
    } 

    return i; 
} 
0
#include<stdio.h> 
#include<string.h> 

int getN(char *); 


int main(){ 
    char str[999]; 
    printf("Enter Sentence: "); gets(str); 
    printf("there are %d words", getN(str)); 
} 


int getN(char *str){ 
    int i = 0, len, count= 0; 
    len = strlen(str); 
    if(str[i] >= 'A' && str[i] <= 'z') 
     count ++; 


    for (i = 1; i<len; i++) 
     if((str[i]==' ' || str[i]=='\t' || str[i]=='\n')&& str[i+1] >= 'A' && str[i+1] <= 'z') 
     count++; 


return count; 
} 
+0

這將工作? – sheehab

0
#include <stdio.h> 

int wordcount (char *string){ 

    int n = 0; 

    char *p = string ; 
    int flag = 0 ; 

    while(isspace(*p)) p++; 


    while(*p){ 
     if(!isspace(*p)){ 
      if(flag == 0){ 
       flag = 1 ; 
       n++; 
      } 
     } 
     else flag = 0; 
     p++; 
    } 

    return n ; 
} 


int main(int argc, char **argv){ 

    printf("%d\n" , wordcount(" hello world\nNo matter how many newline and spaces")); 
    return 1 ; 
} 
-1

這是一個較簡單的函數來計算的話

int counter_words(char* a){` 

// go through chars in a 
// if ' ' new word 
int words=1; 
int i; 
for(i=0;i<strlen(a);++i) 
{ 
     if(a[i]==' ' && a[i+1] !=0) 
     { 
      ++words; 
     } 
} 

return words;}

0

我的數量在完成我正在學習的C課程的功能後,找到了發佈的問題。我從上面發佈的代碼中看到了一些很好的想法。這就是我想出的答案。它當然不像其他的一樣簡潔,但它確實有效。也許這將在未來幫助別人。

我的函數接收一個字符數組。然後,我設置一個指向該數組的指針,以加速該函數的大小。接下來,我找到了要循環的字符串的長度。然後我使用字符串的長度作爲'for'循環的最大值。 然後我檢查正在查看array [0]的指針,看它是否是有效的字符或標點符號。如果指針有效,則增加到下一個數組索引。當前兩次測試失敗時,字計數器會增加。然後該函數將增加任意數量的空間,直到找到下一個有效的字符。 函數在空'0'或找到新行'\ n'時結束。函數會在退出之前最後一次遞增計數,以計及空值或換行符之前的單詞。函數返回計數給調用函數。

#include <ctype.h> 

char wordCount(char array[]) { 
    char *pointer; //Declare pointer type char 
    pointer = &array[0]; //Pointer to array 

    int count; //Holder for word count 
    count = 0; //Initialize to 0. 

    long len; //Holder for length of passed sentence 
    len = strlen(array); //Set len to length of string 

    for (int i = 0; i < len; i++){ 

     //Is char punctuation? 
     if (ispunct(*(pointer)) == 1) { 
      pointer += 1; 
      continue; 
     } 
     //Is the char a valid character? 
     if (isalpha(*(pointer)) == 1) { 
      pointer += 1; 
      continue; 
     } 
     //Not a valid char. Increment counter. 
     count++; 

     //Look out for those empty spaces. Don't count previous 
     //word until hitting the end of the spaces. 
     if (*(pointer) == ' ') { 
      do { 
       pointer += 1; 
      } while (*(pointer) == ' '); 
     } 

     //Important, check for end of the string 
     //or newline characters. 
     if (*pointer == '\0' || *pointer == '\n') { 
      count++; 
      return(count); 
     } 
    } 
    //Redundent return statement. 
    count++; 
    return(count); 
}