알고리즘

C++ 알고리즘 - 백준 1152 단어의 개수

마루설아 2024. 12. 14. 21:10

https://www.acmicpc.net/problem/1152

 

#include <iostream>
#include <string>
using namespace std;

int main(void) {
	// C++ Init
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	string str;
	int cnt = 0;

	getline(cin, str);

	int length = str.length();

	if (length == 1 && str[0] == ' ') {
		cout << 0 << endl;
		return 0;
	}

	for (int i = 1; i < length; i++) {
		if (str[i] == ' ' && str[i+1] != '\0' && str[i+1] != ' ' && str[i + 1] != '\n') cnt++;
	}

	cout << ++cnt;
}

 

 

꽤나 많은 예외사항이 있던 문제.

 

문자열 앞 뒤 공백을 확인해야하고, 공백 하나만 들어온 경우도 생각해야한다.