[첫번째 생각]

 

import java.util.Scanner;

 

public class Main {

 

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();

        int count = 0;

   

        if(str.charAt(0) != ' ') count++;

        for(int i = 1; i <str.length(); i++) {

        if(str.charAt(i - 1) == ' ' && str.charAt(i) != ' ') {

        count++;

        }

        }

        

        if(count == 0) {

        System.out.println("0");

        } else {

        System.out.println(count);

        }

        

        

}

}

 

[문제점 발생]

인덱스관리주의하자.

 

[두번째 생각]

 

 

[훨씬 쉬운 코드]

import java.util.Scanner;

 

public class Main {

 

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String input = sc.nextLine().trim();

        sc.close();

         

        if (input.isEmpty()) {

            System.out.println(0);

        } else {

            System.out.println(input.split(" ").length);

        }

    }

}

 

[결론]

1. next와 nextline의 차이점

next는 공백을 기준으로 한단어를 입력받는다 한문자가  되 ㄹ 수도 있다.

nextline은 전체를 받아온다.

ex. hello next를 입력하면next는 hello ,next line은 hello next

 

2.trim 왼쪽 오른쪽 끝의 공백을 제거해준다.

ex. String input = sc.nextLine().trim();

 

3.split("*")

*를 기준으로 string이 구분되어진다.

 

split("*",2)

*를 기준으로 string이 구분되어지는데, 2개만 만든다.

 

+ Recent posts