簡體   English   中英

計算char數組C ++中的單詞數

[英]Counting number of words in char array C++

我正在研究一種算法,該算法將計算char數組中的單詞數。 到目前為止,它似乎無法正常工作。 當字符到達並且不是空格時,應將其視為單詞的一部分。 一旦您到達空白處,我們將一言不發。 例如,由於“ hello”和“ world”之間存在空格,因此“ Hello World”是兩個單詞。

碼:

for(int l = 0; l < count; l++){
        if(isalpha(letters[l]) && !in_word){
            num_words++;
            in_word = true;     
        }else{
            in_word = false;
        }
    }

示例輸入:aaaaa bbb aaa lla bub www

樣本輸出:13個字

期望的輸出:6個字

可能的答案:

for(int l = 0; l < count; l++){
        if(isalpha(letters[l]) && !in_word){
            num_words++;
            in_word = true;     
        }else if(!isalpha(letters[l])){
            in_word = false;
        }
    }

單步執行該代碼(在調試器中,用紙在頭/紙上)。

給定輸入“ abc def”

最初假設in_word = false

  • 第一個字符為'a', in_word為false,因此num_words++in_word=true
  • 下一個字符是'b', in_word為true,因此in_word=false

希望你會發現什么地方出了問題

簡單的方法:修剪字符串,計算空格,加1

如果您想對換行符,空格標點符號等進行很好的處理,則可以使用正則表達式。 您甚至可以使它適應於utf-8字符串。 但是,它需要C ++ 11支持。

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("this subject has a submarine as a subsequence");
  std::smatch m;
  std::regex e ("\\b(\w*)\\b")

  int count = 0;
  while (std::regex_search (s,m,e)) {
    ++count;
    s = m.suffix().str();
  }

  std::cout<<"Number of matches = "<<count<<std::endl;

  return 0;
}

暫無
暫無

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

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