簡體   English   中英

如何計算在 c 中的字符串中找到的單詞數

[英]How to count number of words found in a string in c

我正在嘗試編寫一個程序來計算在字符串中找到的單詞數,但是我編寫的程序會計算空格數。 我如何構建這個程序 - 盡可能高效 - 來計算字數? 我該怎么說字符串包含 4 個單詞和 8 個空格,或者如果它不包含單詞而只包含空格? 我錯過了什么/做錯了什么?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
int count_words = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
    if (isspace (text[i]))
    {
        count_words++;
    }
}
printf("%i\n", count_words + 1);
}

檢測和計算單詞的開頭,空格到非空格的轉換:

int count_words = 0;
bool begin = true;
for (int i = 0, n = strlen(text); i < n; i++) {
  if (isspace (text[i])) {
    begin = true;
  } else {
    if (begin) count_words++;
    begin = false;
  }
}

試試這個條件來計算單詞:

if(text[i]!=' ' && text[i+1]==' ')
        Count=count+1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM