第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;
}

运行结果:



学习心得:

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值