[Java | 백준 1152] 단어의 개수
· 테크· Java
Java
백준 1152번 www.acmicpc.net/problem/1152
풀이
입력된 값을 문자열로 받고, 그 문자열을 charAt() 을 이용해서 한 문자씩 ' ' 공백이 맞는지 확인한다.
여기서 주의할 점은 공백이 앞이나 뒤에 올 수 있다는 것이다.
다시 생각하면 앞 뒤 공백이 없다면 문자열에 있는 공백의 수 +1 값이 단어의 수가 된다. 따라서 공백이 나올 때마다 cnt 로 숫자를 세어준다. 그리고 결과 값에서 +1 을 해준다.
마지막으로 앞서 생각한 주의점을 고려해주는데, 앞 뒤 공백 값은 단어 수에 영향을 미치면 안 되므로 그 경우에는 cnt 를 차감해준다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.*;
public class String_1152 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int cnt=0;
int last = str.length();
if(str.charAt(0)==' ') cnt--;
if(str.charAt(last-1)==' ') cnt--;
for (int i=0; i<last; i++) {
if(str.charAt(i)==' ')
cnt++;
}
System.out.println(cnt+1);
sc.close();
}
}
|
cs |
Comments
No comments yet. Be the first!
319 posts in 테크
- 368Supabase 프로젝트 복사하기 (Restore to a New Project)NEW
- 341Migrating from Permanent Access Tokens to Token Exchange — Why Order Matters
- 326Startup & Product Glossary: Terms Every Solo Founder Should Know
- 325Context Management — How I Do It Now
- 324Claude Code Routines vs Cowork Schedule — What's the Difference?
1–5 / 319