c++(字符串操作 1)

Function: 统计一行字符串中 的单词个数,并将 每个单词首字母 变为大写字母

  1 /*
  2  * File: lineword.cpp
  3  * ------------------
  4  * This program converts initial letter of every word in line to upper.
  5  */
  6 
  7 #include <iostream>
  8 #include <string>
  9 
 10 std::string lineToWord(std::string line);
 11 std::string wordToUpper(std::string word);
 12 
 13 int num; //number of words in line
 14 
 15 int main()
 16 {
 17         std::string line;
 18         num = 0;
 19         std::cout<< "please enter string message: ";
 20         getline(std::cin, line);
 21         std::cout<< "result:[ " << num << " words ] "<< lineToWord(line) << std::endl;
 22 
 23         return 0;
 24 }
 25 
 26 /*
 27  * Function: lineToWord
 28  * Usage: string translation = lineToWord(word);
 29  * ---------------------------------------------
 30  * acquire every word in line.
 31  */
 32 
 33 std::string lineToWord(std::string line)
 34 {
 35         std::string result = "";
 36         int start = -1; //是否为单词的首字母的标识符
 37         for(int i = 0; i < line.length(); i++)
 38         {
 39                 char ch = line[i];
 40                 if(isalpha(ch)) //isalpha()函数,判断字符是否为一字母
 41                 {
 42                         if(start == -1) start = i;
 43                 }
 44                 else
 45                 {
 46                         if(start >= 0)
 47                         {
 48                                 result += wordToUpper(line.substr(start, i - start));  //.substr(),截取输入行中的单词
 49                                 start = -1;
 50                         }
 51                         result += ch;   //加上非字母的其它字符
 52                 }
 53         }
 54         if(start >= 0) result += wordToUpper(line.substr(start));  //处理最后一个单词
 55         return result;
 56 }
 57 
 58 /*
 59  * Function: wordToUpper
 60  * Usage: string word = wordToUpper(word);
 61  * ---------------------------------------
 62  * convert the initial letter of word to upper letter
 63  */
 64 
 65 std::string wordToUpper(std::string word)
 66 {
 67         char ch = toupper(word[0]);  //toupper(),转换为大写字母
 68         word = ch + word.substr(1);
 69         num++;
 70         return word;
 71 }


执行



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值