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 }