如何计算C++字符数组中的单词
How to count words from an array of chars in C++
我在尝试将字符数组中的字母接收到我的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
的' '
字符。要读取字符串/字符数组的每个字符,您只需使用索引运算符 []
。与其他数组一样,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] != ' '); 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] != ' '); 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;
}
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符