728x90
반응형
앞 뒤 공백을 제거할 때 사용하는 유용한 방법을 발견
string.find_first_not_of(' ')는 문자열 input에서 ' ' 공백이 아닌 첫 번째 문자의 위치는 찾는다.
즉, input.erase(0,input.find_first_not_of(' '))는 0부터 공백이 아닌 첫 번째 문자 앞까지 지운다.
뒤에 find_last_not_of(' ')도 동일한 동작을 한다.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string input;
getline(cin,input);
input.erase(0,input.find_first_not_of(' '));
input.erase(input.find_last_not_of(' ')+1);
int word_count = count(input.begin(), input.end(), ' ') + 1;
if (input.empty()) {
word_count = 0;
}
cout << word_count << endl;
return 0;
}
728x90
반응형
'Baekjoon > Bronze' 카테고리의 다른 글
Baekjoon 2292.벌집 c++ [Bronze II] (0) | 2024.11.10 |
---|---|
Baekjoon 2231. Digit Generator c++ [Bronze II] (0) | 2024.11.06 |
Baekjoon 10809. 알파벳 찾기 c++[Bronze II] (0) | 2024.11.03 |
Baekjoon 18698. The Walking Adam c++[Bronze IV] (0) | 2024.10.24 |
Baekjoon 2605. 줄세우기 c++[Bronze II] (0) | 2024.10.23 |