Post

String_문장 속 단어_split, subString, indexOf

✅ 한 개의 문장이 주어지면 그 문장 속에서 가장 긴 단어 출력하기

🔵 String.split(" ") 으로 문장을 띄어쓰기 단위로 나누기

🔵 Get maximum

1
2
3
4
int min= Integer.VALUE_MINIMUM();
if( max > min){
    min = max;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Main {
    public String solution(String str){
        String answer= "";
        String[] strArr = str.split(" ");
        int min= Integer.MIN_VALUE;
        for(String x : strArr ){
            if(x.length()> min){
                min= x.length();
                answer= x; //answer에다가 가장 긴 단어를 저장
            }
        }
        return answer;
    }
    public static void main(String[] args){
        Main T = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        System.out.println(T.solution(str));
    }

}

//⭐️input:
//it is time to study
//⭐️output:
//study

🟡 indexOf(), subString()

💡 indexOf() returns the position of the first occurrence of specified character(s) in a string
💡 lastIndexOf method to return the position of the last occurrence

💡 subString() public String substring(int begIndex, int endIndex);
여기서부터 여기까지!

String.split(" ")을 쓰지 않고 indexOf(), subString()사용해서 풀기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;

class Main {
    public String solution(String str){
        String answer= "";
        int min= Integer.MIN_VALUE, pos;
        while((pos= str.indexOf(' ')) !=-1){
            String tmp= str.substring(0, pos);
            if(tmp.length() > min){
                min= tmp.length();
                answer= tmp;
            }
            //이제 pos, tmp 구한 단어는 잘라내 주어야 한다.
            str= str.substring(pos+1); //시작부터 끝까지 잘라내기
        }
        //마지막 단어 처리해주기
        if(str.length() > min) answer= str;
        return answer;
    }


    public static void main(String[] args){
        Main T = new Main();
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        System.out.println(T.solution(str));
    }

}
  1. while문이 돌아가고, 띄어쓰기 유무가 -1이 아닐 때,
  2. pos라는 변수에 indexOf()를 사용해 처음으로 띄어쓰기가 등장하는 위치를 지정한다.
  3. subString()을 사용해 0번 인덱스부터 띄어쓰기가 등장하는 pos까지 단어를 잘라내서 저장한다.
  4. 이 단어의 길이가 전 단어의 길이보다 길다면 answer에 새롭게 저장한다.
  5. 지금까지 길이 구한 단어는 subString()을 사용해 잘라내 버린다. 새롭게 str을 만들고 위 과정을 반복한다.
  6. 그런데 마지막 단어 뒤에는 띄어쓰기가 없다.
  7. 마지막 단어가 가장 긴 단어인 경우를 처리하기 위해 마지막 단어가 여태까지 구한 단어들의 길이보다 길다면, 정답에 다 잘라내고 남은 단어를 저장한다.

🔵 ThingsILearned

✔️ String.split(" ") 으로 문장을 띄어쓰기 단위로 나누기

✔️ How to get maximum, minimum

✔️ indexOf(), subString()

🔴 Trouble Shooting

✔️ sc.nextLine();

String str = sc.nextLine();을 하는데 만약
String str = sc.next();만 하면 하나의 단어만 읽어온다는 걸 명심하자!

✔️ indexOf(), subString()을 사용했을 때 마지막 단어가 가장 긴 경우

마지막 단어 뒤에는 띄어쓰기가 없다. 그래서 마지막 단어만 남았을 때 pos= str.indexOf(' ')를 하면 거짓이라 마지막 단어는 넘어가게 된다.
이를 해결하기 위해 만약 마지막 단어의 길이가 지금까지 구한 단어의 길이보다 길다면,
정답에 마지막 단어를 저장해야 한다.

This post is licensed under CC BY 4.0 by the author.