我一直在嘗試創建一個從檔案中讀取文本并將其存盤在字串中的程式。我將字串提供給一個函式,該函式對字串中的每個單詞進行計數。
然而,假設用戶在行尾留下一些空白并且不創建空行,它唯一的準確度是......不是一個很好的單詞計數器。
- 創建一個空行會導致字數錯誤增加。
我不確定我的主要問題是使用布林值來執行此操作還是檢查空格和 '\n' 字符。
bool countingLetters = false;
int wordCount = 0;
for (int i = 0; i < text.length(); i )
{
if (text[i] == ' ' && countingLetters == true)
{
countingLetters = false;
wordCount ;
}
if (text[i] != ' ' && countingLetters == false)
{
countingLetters = true;
}
if (text[i] == '\n' && countingLetters == true)
{
countingLetters = false;
wordCount ;
}
}
uj5u.com熱心網友回復:
您的代碼基本上是一個狀態機。要完成您的解決方案,只需計算字串結尾。
將此添加到代碼的末尾:
if(countingLetters) { // word at the end of string, without any space charactor
wordCount ;
}
或者,如果您可以確定它是 C 風格的字串,例如 std::string,您可以只索引 1 傳遞最后一個字符,并'\0'以相同的方式處理空格和'\n'.
要改進您的代碼,請使用 isspace(這涵蓋了更多的空格字符,包括'\t'等)。最好使用else if模式。此外,這不是一個好習慣==true。只需使用布林值作為條件。
或者,也許isalpha(c)更適合您的需要。
bool countingLetters = false;
int wordCount = 0;
for (char c:text) {
if (!isalpha(c) && countingLetters) { // this also works for newline
countingLetters = false;
wordCount;
} else if (isalpha(c) && !countingLetters) {
countingLetters = true;
} // otherwise just skip
}
if(countingLetters) { // word at the end of string, without any space charactor
wordCount;
}
并且為這樣一個簡單的任務插入額外的字符是不可接受的。例如,文本可能是常量。
uj5u.com熱心網友回復:
另一種方法是計算“單詞”的開頭。
假設一個單詞的開頭是一個非字母之后的字母。如果需要,我們可以調整它。
int wordCount = 0;
int prior = '\n'; // some non-letter
for (int i = 0; i < text.length(); i ) {
if (isalpha(text[i]) && !isalpha(prior)) {
wordCount ;
}
prior = text[i];
}
uj5u.com熱心網友回復:
C 還提供了一些非常高級的方法來做到這一點。
一種是在字串流上使用回圈,它在空白處拆分文本:
#include <sstream>
#include <string>
std::size_t count_words( const std::string& s )
{
std::size_t count = 0;
std::istringstream ss( s );
std::string t;
while (ss >> t) count = 1;
return count;
}
另一個是使用流迭代器演算法:
#include <iterator>
#include <sstream>
#include <string>
std::size_t count_words( const std::string& s )
{
std::istringstream ss( s );
return std::distance(
std::istream_iterator <std::string> ( ss ),
std::istream_iterator <std::string> ()
);
}
還有一個是使用正則運算式:
#include <iterator>
#include <regex>
#include <string>
std::size_t count_words( const std::string& s )
{
std::regex re( "\\w " );
return std::distance(
std::sregex_iterator( s.begin(), s.end(), re ),
std::sregex_iterator()
);
}
我敢肯定還有更多,但這三個是我頭頂上的那些。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355604.html
上一篇:如何將一堆資料添加到鏈表中
