-
1152) 단어의 개수 c++백준코딩일기 2021. 1. 13. 20:30
문제 ) www.acmicpc.net/problem/1152
풀이 ) c++ 에서 입력받을 때, 자연스럽게 쓰던 cin 을 버리고 getline으로 입력받는게 이번 문제의 키워드였을 것 같다.
1. getline 을 이용해서 입력을 받고
2. 입력받은 문자열이 비었다면 0을 출력하고
아니라면 count = 1 로 초기화해서
3. 반복문을 통해 띄어쓰기를 만나면 count++ 을 하게 했다.
4. 하지만 맨 처음이 띄어쓰기로 시작할 수도 있기에, 그 경우는 count-- 를 해주고
5. 맨 마지막이 띄어쓰기일경우도 count-- 를 해서 출력한다.
count -- 를 하는 이유는 count가 단어의 개수를 세는 것이기 때문이다.
코드 )
#include <iostream> using namespace std; string str; int main(void) { getline(cin,str); int count = 0; if(str.empty()) { cout << "0"; return 0; } count = 1; for(int i = 0; i < str.length(); i++) { if(str[i] == ' ') count++; } if(str[0] == ' ') count--; if(str[str.length()-1] == ' ') count--; cout << count; }
'백준코딩일기' 카테고리의 다른 글
10844) 쉬운 계단 수 c++ (0) 2021.02.04 11057) 오르막 수 c++ (0) 2021.02.04 15666) N과 M (12) c++ (0) 2020.12.11 15665) N과 M (11) c++ (0) 2020.12.11 15664) N과 M (10) c++ (0) 2020.12.11