Baekjoon/Bronze

Baekjoon 1152. 단어의 개수 c++[Bronze II]

Hun-bot 2024. 11. 3. 20:54
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
반응형