C ++函数来计算字符串中的所有单词 [英] C++ function to count all the words in a string
问题描述
在一个面试中我被问过这个问题,显然这是一个简单的问题,但是对我来说还不是很明显。所有的字。如果他们重复无关紧要。只是总计数像一个文本文件字数。单词是由空格分隔的任何东西,标点符号无关紧要,只要它是单词的一部分。
例如:
一个非常,非常,非常非常大的狗吃了我的家庭作业! ==> 11个字
我的算法只是通过寻找空格和增加计数器直到我命中null。因为我没有得到的工作,被要求离开后,我想我的解决方案不好?任何人都有更聪明的解决方案?我缺少一些东西?
一个不那么聪明,更明显的程序员-team方法。
#include< cctype&
int CountWords(const char * str)
{
if(str == NULL)
return error_condition; //让需求定义这个...
bool inSpaces = true;
int numWords = 0;
while(* str!= NULL)
{
if(std :: isspace(* str))
{
inSpaces = true;
}
else if(inSpaces)
{
numWords ++;
inSpaces = false;
}
++ str
}
return numWords;
}
I was asked this during an interview and apparently it's an easy question but it wasn't and still isn't obvious to me.
Given a string, count all the words in it. Doesn't matter if they are repeated. Just the total count like in a text files word count. Words are anything separated by a space and punctuation doesn't matter, as long as it's part of a word.
For example:
A very, very, very, very, very big dog ate my homework!!!! ==> 11 words
My "algorithm" just goes through looking for spaces and incrementing a counter until I hit a null. Since i didn't get the job and was asked to leave after that I guess My solution wasn't good? Anyone have a more clever solution? Am I missing something?
A less clever, more obvious-to-all-of-the-programmers-on-your-team method of doing it.
#include <cctype>
int CountWords(const char* str)
{
if (str == NULL)
return error_condition; // let the requirements define this...
bool inSpaces = true;
int numWords = 0;
while (*str != NULL)
{
if (std::isspace(*str))
{
inSpaces = true;
}
else if (inSpaces)
{
numWords++;
inSpaces = false;
}
++str;
}
return numWords;
}
这篇关于C ++函数来计算字符串中的所有单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!