开发者社区> 问答> 正文

不调用任何库函数如何实现stat_word.求大神打救

请保证代码工整,关键部分请用注释对代码逻辑进行说明
不调用任何库函数实现stat_word,该函数的功能是从字符串str中统计单词个数,str完全由英文字母及空格符组成,连续出现的若干个非空格字符即为一个单词。(5分)
int stat_word(const char* str);

展开
收起
a123456678 2016-03-05 09:50:07 1907 0
2 条回答
写回答
取消 提交回答
  • 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;
    }

    2019-07-17 18:52:58
    赞同 展开评论 打赏
  • 代码附上:

    #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;
    }
    2019-07-17 18:52:58
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载