gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:50:00 25 4
gpt4 key购买 nike

我在尝试将字符数组中的字母接收到我的 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;
}

最佳答案

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

这里是一个 for 循环的例子,它将一个字符串的一个字符读入一个字符变量。

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;
}

关于c++ - 如何计算 C++ 中字符数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com