请保证代码工整,关键部分请用注释对代码逻辑进行说明
不调用任何库函数实现stat_word,该函数的功能是从字符串str中统计单词个数,str完全由英文字母及空格符组成,连续出现的若干个非空格字符即为一个单词。(5分)
int stat_word(const char* str);
int star_word(const char* str)
{
const char* p = str;
int nRet = 0;//统计到的单词数
while(p!=NULL && *p != '0')//当遍历到字符串尾部时结束循环
{
if(p!=' '&&(p+1) == ' ')//如果当前字符不是空格,下一个是空格,则认为是一个单词
{
nRet++;
}
++p;
}
return nRet;
}
代码附上:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int stat_word(const char* str)
{
int num=0;
int word=0;
while(*str!='\0')
{
if(word==0)
{
if(*str++!=' ')
{
num++;
word=1;
}
}
else if(*str++==' ')
{
word=0;
}
}
return num;
}
int main()
{
cout<<stat_word("hello, World!")<<endl;
return 0;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。