Algorithm
[백준 - 1152번] 단어의 개수
1984
2022. 1. 21. 08:49
- trim 구현
- 아무것도 입력 안 되어 있을 때, 예외 처리하기
#include <iostream>
#include <string>
using namespace std;
inline string& left_trim(string& s, const char* t = " \t\n\r\f\v")
{
s.erase(0, s.find_first_not_of(t));
return s;
}
inline string& right_trim(string& s, const char* t = " \t\n\r\f\v")
{
s.erase(s.find_last_not_of(t) + 1);
return s;
}
inline string& trim(string& s, const char* t = " \t\n\r\f\v")
{
return left_trim(right_trim(s, t), t);
}
int main(void)
{
string s;
int count = 0;
getline(cin, s);
s = trim(s);
if (s.size() != 0) {//단어가 입력 안 됐을 때 예외 처리
for (int i = 0; i < s.size(); i++)
{
if (s.at(i) == ' ')
{
count++;
continue;
}
}
count++; //단어 수 = 공백 수 + 1
}
cout << count;
}
[참고 자료]
728x90