/**
* Copyright (C) 2014, CSU
* All rights reserved
* File Name:test.cpp
* Author: lmm
* Date of completion: 2015/1/12
* Version: v1.0
*
* 问题描述:字符串最后一个单词的长度
* 输入描述: 计算字符串最后一个单词的长度,单词以空格隔开,一行字符串,长度小于128,例如 输入“I am a student”
* 知识点 : 字符串,循环
* 程序输出: 输出整数N,最后一个单词的长度
*/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cctype>
using namespace std;
int main()
{
char str[128] = "";
gets(str);
int length_str = strlen(str); // 字符串长度
int length_word = 0; // 单词长度
int spaceSum = 0; // 非字母的字符
for (int i = length_str-1; i >=0; --i)
{
if ((str[i] == ' ')||(!isalpha(str[i])))
{
spaceSum++;
}
else
break;
}
for (int i = length_str-spaceSum-1; i >=0; --i)
{
if ((str[i] == ' ')||(!isalpha(str[i])))
{
break;
}
else
{
length_word++;
}
}
cout << length_word << endl;
return 0;
}
注意:刚开始觉得此题简单,也好久没写代码了,其则分析时候没考虑周到,则容易出现错误。
错误原因:1.没有考虑最后一个单词还有空格 例如:hello world(空格)
2.没有考虑最后一个单词还有多个空格 例如:hello world(多个空格)
3.假如最后单词的字母存在非字母的情况 例如:hello wor*ld(多个空格)*&(空格)#@
总结:1.一个问题逻辑分析比写代码更重要
2.代码实现要选择各种情况下的测试用例,测试用例的选择前提分析到位,考虑到各种情况。
3.可以使用C++函数,例如统计字母的个数isalpha(),则方便很多。
4.cctype头文件中很多函数可以运用到代码中
isalnum(c) //如果c是字母或数字,则为true
isalpha(c) //如果c是字母,则为true
iscntrl(c) //如果c是控制字符,则为true
isdigit(c) //如果c是数字,则为true
isgraph(c) //如果c不是空格,则为true
islower(c) //如果c是小写字母,则为true
isprint(c) //如果c是可打印字符,则为true
ispunct(c) //如果c是标点符合,则为true
isspace(c) //如果c是空白符合,则为true
isupper(c) //如果c是大写,则为true
isxdigit(c) //如果c是十六进制数,则为true
tolower(c) //如果c是大写字母,则返回其小写字母形式,否则直接返回0
toupper(c) //如果c是小写字母,则返回其大写写字母形式,否则直接返回0