728x90
1152번: 단어의 개수
첫 줄에 영어 대소문자와 띄어쓰기로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 띄어쓰기 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한
www.acmicpc.net
1) 주석 없는 VERSION
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
int count = 1;
getline(cin, s);
for (int i = 0;i < s.length();i++) {
if (s[i] == ' ') {
count++;
}
}
if (s[0] == ' ' || s[0] == '\0') {
count--;
}
if (s[s.length() - 1] == ' ') {
count--;
}
cout << count;
}
2) 주석 있는 VERSION
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
int count = 1; // 첫 단어는 띄어쓰기 다음이 아니므로
getline(cin, s); // 띄어쓰기도 문자열로 받도록 getline 함수 사용
for (int i = 0;i < s.length();i++) {
if (s[i] == ' ') {
count++; // 띄어쓰기 있을 때마다 count 1증가
}
}
if (s[0] == ' ' || s[0] == '\0') { // 첫문자가 공백인 경우 빼주기
count--;
}
if (s[s.length() - 1] == ' ') { // 마지막 문자가 공백인 경우 빼주기
count--;
}
cout << count;
}
❌주의사항❌
띄어쓰기도 문자로 읽을 경우
getline 함수 사용하기
'BEAKJOON' 카테고리의 다른 글
백준(5622번 다이얼)풀이 C++ (0) | 2021.01.10 |
---|---|
백준(2908번 상수)풀이 C++ (0) | 2021.01.10 |
백준(1157번 단어 공부)풀이 C++ (0) | 2021.01.09 |
백준(2675번 문자열 반복)풀이 C++ (0) | 2021.01.09 |
백준(10809번 알파벳 찾기)풀이 C++ (0) | 2021.01.09 |