ORIGIN

HDU-2026 首字母变大写

ACM 1 mins330 words

首字母变大写

输入一个英文句子,将每个单词的第一个字母改成大写字母。

Input

输入数据包含多个测试实例,每个测试实例是一个长度不超过100的英文句子,占一行。

Output

请输出按照要求改写后的英文句子。

Sample Input

1
2
i like acm
i want to get an accepted

Sample Output

1
2
I Like Acm
I Want To Get An Accepted

Analysis

  1. traverse the string to upper the letters.

    The point of this problem is to input a string with spaces.

    If you use string, you can use

    1
    getline(cin, string);

    If you use char array, you can use

    1
    cin.getline(str,len);

    Since you don’t know the length, you choose the first one;

    And another thing is that to make the letter an uppercase letter, you can just make the character minus 32 which means subtract the ascii code.

    eg. 'a' - 32 = 'A'

  2. using stringstream to traverse words.

    stringstring can make the sentence sperate by spaces or other special character.

Code

Method 1: traverse letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<bits/stdc++.h>

using namespace std;

int main() {
string sentence;
while(getline(cin, sentence)) {
sentence[0] -= 32;
for(int i = 1; i < sentence.length(); i ++) {
if(sentence[i - 1] == ' ') {
sentence[i] -= 32;
}
}
cout << sentence << endl;
}
return 0;
}

Method 2: traverse words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<bits/stdc++.h>

using namespace std;

int main() {
string sentence, word;
while(getline(cin, sentence)) {
stringstream ss(sentence);
ss >> word;
word[0] -= 32;
cout << word;
while(ss >> word) {
word[0] -= 32;
cout << " " << word;
}
cout << endl;
}
return 0;
}
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|