백준
백준 1152번 '단어의 개수' (JAVA 11)
ho코딩
2024. 1. 3. 11:56
백준 1152번인 '단어의 개수'를 나타내는 문제입니다.
단어 개수는 공백을 기준으로 나뉘며, 공백의 개수를 구하여 출력하는 형식으로 풀이를 했습니다.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String w=scan.nextLine().trim();
int count=1; // 공백
if(w.isEmpty()){
System.out.println("0");
}
else{
for(int i=0; i<w.length(); i++){
if(w.charAt(i)==' '){
count++;
}
}
System.out.println(count);
}
}
}
public class Main {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String w=scan.nextLine().trim();
int count=1; // 공백
if(w.isEmpty()){
System.out.println("0");
}
else{
for(int i=0; i<w.length(); i++){
if(w.charAt(i)==' '){
count++;
}
}
System.out.println(count);
}
}
}
앞선 문제들과 같이 Scanner(System.in)의 scan 객체를 생성하여
생성한 scan 객체를 사용하여 변수 w에 문자열을 입력 받습니다.
Scanner scan = new Scanner(System.in);
String w=scan.nextLine().trim();
이때 .trim()은 문자열의 앞과 끝쪽의 공백을 제거하는 함수이며 공백으로 시작하거나 공백으로 끝나는 경우,
이를 단어로 인식함을 방지하기 위해 사용해줍니다.
또한 공백의 개수를 카운트하기 위한 변수 count를 설정해주고 초기값으로 '1'을 설정합니다.
초기값으로 '1'을 설정하는 이유는 공백이 하나도 없이 단어 하나만 있는 경우를 기본값으로 두기 위함입니다.
이후 if문을 활용하여, 문자열이 아예 비어있는 상태라면 '0'을 출력하도록 하고,
그렇지 않다면 공백을 카운트하는 코드를 작성합니다.
if(w.isEmpty( ) ) {
System.out.println("0");
}
else{
for(int i=0; i<w.length(); i++){
if(w.charAt(i)==' '){
count++;
}
}
끝으로 공백의 개수를 카운트한 count 변수를 출력합니다.
System.out.println(count);