494 - Kindergarten Counting Game

解析UVA在线裁判题:数单词问题
本文深入解析了UVA在线裁判平台上的数单词问题,通过使用C++编程语言实现,详细阐述了解题思路及代码实现,旨在帮助初学者掌握字符串处理和输入输出操作的基本技巧。

思路:

数单词, 从头到尾遍历每一行, 碰到连续的字母就开始/继续一个单词, 否则就结束一个单词. 注意两点:

1. 用 isalpha() 判断是否为字母(<cctype>)

2. 用 getline() 来读入一行带有空格的字符串

题目: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem&problem=435

代码:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main(int argc, char const *argv[])
{
    string str;
    getline(cin, str);

    while ( !cin.eof() ){
        int count = 0;
        bool newWorld = false;

        int length = str.length();
        for(int i=0; i<length; i++){
            if( isalpha(str[i]) ){
                if( !newWorld ){
                    newWorld = true;
                }
            }else{
                if( newWorld ){
                    ++count;
                    newWorld = false;
                }
            }
        }

        // 如果最后一个是字母, 则要添加对最后一个单词的统计
        if( isalpha(str[length-1]) ){
            ++count;
        }

        cout << count << endl;
        getline(cin, str);
    }

    return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

转载于:https://my.oschina.net/zenglingfan/blog/136965

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值