BOJ::문제풀이
1152 단어의 개수
2영재
2017. 12. 30. 22:32
BOJ::1152 단어의 개수
https://www.acmicpc.net/problem/1152
자바에서는 StringTokenizer 클래스를 이용하여 아주아주 쉽게 풀 수 있지만.....
C++로 풀때는 자꾸 틀렸다고 나오길래 왜그러지 하고 생각해보니..
맨처음과 맨 마지막에 ' ' 띄어쓰기가 나올 수 있었다... 그것만 처리해주면 된다.
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; class Main{ public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int cnt=0; while(st.hasMoreTokens()){ cnt ++; st.nextToken(); } System.out.println(cnt); } } | cs |
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <iostream> #include <string> using namespace std; int main() { string s; getline(cin, s); int cnt = 0,n; n = s.length(); for (int i = 0; i < n; i++) { if (s.at(i) == ' ') { cnt++; } } if (s.at(0) == ' ') { cnt--; } if (s.at(n - 1) == ' ') { cnt--; } cout << ++cnt << endl; } | cs |