第16周项目2-用指针玩字符串(统计字符串中单纯词个数)

第16周项目2--用指针玩字符串(统计字符串中单词个数)
/* 
* Copyright (c) 2014, 烟台大学计算机学院 
* All rights reserved. 
* 文件名称:test.cpp 
* 作    者:刘畅 
* 完成日期:2014 年 12  月  13  日 
* 版 本 号:v1.0 
* 
* 问题描述:用指针作形参,其核心是实现int (char *str)函数。; 
* 输入描述:无需输入; 
* 程序输出:输出要求输出的。


#include <iostream>
using namespace std;
int pwordnum(char *str);
int main()
{
    char s1[50]="Hello world. ";
    char s2[50]="Good morning. ";
    char s3[50]="vagetable bird! ";
    cout<<"各字符串中单词个数依次为:"<<endl;
    cout<<s1<<pwordnum(s1)<<endl;
    cout<<s2<<pwordnum(s2)<<endl;
    cout<<s3<<pwordnum(s3)<<endl;
    return 0;
}

int pwordnum(char *str)
{
    int i,flag,count;
    flag = 0;
    count = 0;
    for(i = 0; *(str+i)!='\0'; i++)
    {
        if(*(str+i) == ' ')
            flag = 0;
        else if(flag == 0)
        {
            flag = 1;
            count++;
        }
    }
    return count;
}

运行结果:

第16周项目2-用指针玩字符串(统计字符串中单纯词个数)


学习心得:

字符串中的空格和结束时的空字符还真是不好处理,,,写了好几种表达都不行,最后还是借助了度娘,唉唉,继续加油吧!