如何在C ++中计算字符数组中的单词

时间:2019-04-06 01:53:07

标签: c++ algorithm function char word-count

我在尝试将字符数组中的字母接收到我的wordCount函数中以计算数组中每个项目的单词数时遇到问题。我相信我应该只操作该函数,但不清楚如何将testCases数组中的各个字母放入单词计数函数中。

在那之后,我假设我将使用if语句来检查读入wordCount的字符是否为字母,以及何时将其计数为单词。

以下代码:

#include <iostream>
using namespace std;

// Function Prototype
int wordCount (char *userEntry);

int main() {
// Constants
const int MAX_LENGTH = 150;

// Local variables
char testCases[][MAX_LENGTH + 1] = { "0",
    "    1   22    3333    44444 ",
    "     testing    ",
    "a",
    "onetwothree",
    "one two three",
    "    testing    a    11   222  three  4  five  ",
    "a b c d e f" };
int wCount = 0;

// loop through test cases and display number of words in each
for (char *entry : testCases) {
    wCount = wordCount(entry);
    cout << "\nNumber of words in the test case '" << entry << "' is: " 
<< wCount << endl;
}

return EXIT_SUCCESS;
}

/*
Function Name:  wordCount
This function counts the # of space-delimited words
in a character string, and returns the count to the
caller.
NOTE: A word is defined as one or more alphabetic
characters separated by one or more spaces,
unless it is the only alphabetic character(s).
*/

int wordCount (char *userEntry) {

return 0;
}

1 个答案:

答案 0 :(得分:2)

c ++中的字符串以null终止,这意味着在它们的最后一个字符之后有一个'\0'字符,其字符代码为0x00。要读取字符串/字符数组的每个字符,只需使用索引运算符[]。像其他数组一样,C ++中的字符串的索引从0到n-1

这是循环的示例,该循环会将字符串的字符读入字符变量。

void iterate_through_characters(const char* aString) {
    // starting at n=0 check each n and make sure it is shorter than the
    // width of the array
    // and that it's not the null terminating character
    for (int n = 0; (n < MAX_LENGTH + 1) && (aString[n] != '\0'); n++) {
        // take the character out of the index in the string and store it in aCharacter
        char aCharacter = aString[n];
    }
}

对于您的特殊情况,您还希望跟踪自己是否已经在一个单词中,并且仅在单词尚未使用时才计算一个新单词。下面的函数实现了这一点。

int wordCount(const char* input) {

    // this is true if we're in a word
    bool inWord = false; 

    // the number of words we've seen defaulting to 0, no words
    int result = 0;

    for (int n = 0; (n < MAX_LENGTH + 1) && (aString[n] != '\0'); n++) {
       // if this is a space we're not in a word
       if (aString[n] == ' ') {
           inWord = false; // if we were in a word, we aren't now
       } else if (!inWord) {
           inWord = true; // if we weren't in a word, we are now
           result ++; // increment the number of words we've seen 
       }
   }
   return result;
}