본문 바로가기
알고리즘/문자열, 정렬

[알고리즘] 문장 속 단어 with Java, nextLine(), indexOf(),subString()

by VIPeveloper 2022. 2. 24.
반응형

알고리즘 공부 2일차 ! 오늘도 화이팅 해보자.

오늘 배운 것

1. nextLine()

next()가 문자열을 읽는 것(띄어쓰기 전까지) 이라면, nextLine()은 한줄을 그대로 읽는 것이다.

// test = "it is time to study";
System.out.println(test.next());	// it
System.out.println(test.nextLine());	// it is time to study

2. indexOf(char c)

param으로 주어진 문자의 첫번째 인덱스를 반환한다. 없다면 -1을 반환해준다.

String test = "it is time to study";
System.out.println(test.indexOf('i'));	// 0
System.out.println(test.indexOf('t'));	// 1
System.out.println(test.indexOf('s'));	// 4
System.out.println(test.indexOf(' '));	// 2
System.out.println(test.indexOf('x'));	// -1

3. subString(int i)

i까지의 인덱스를 포함하여 그 이후까지 값을 반환한다. 새로운 메모리에 참조시킬 수 있다.

String test = "it is time to study";
String test1 = test.substring(test.indexOf(' ')+1);
System.out.println(test1);	// is time to study

4. 문제 풀이

import java.util.Scanner;

public class Main {

    public static String solution(String str) {
        String answer = "";
        int max_length = Integer.MIN_VALUE,pos;
        while ((pos = str.indexOf(' ')) != -1){
            String test = str.substring(0,pos);
            int len = test.length();
            if (max_length < len){
                max_length = len;
                answer = test;
            }
            str = str.substring(pos+1);
        }
        if(answer.length() < str.length()){
            answer = str;
        }

        return answer;
    }

    public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);
        String str = kb.nextLine();
        System.out.println(solution(str));

    }
}
반응형