한 개의 문장이 주어지면 그 문장 속에서 가장 긴 단어를 출력하는 프로그램을 작성하세요.
문장 속의 각 단어는 공백으로 구분됩니다.
it is time to study
study
// (1)
import java.util.Scanner;
public class Main {
public String solution(String str) {
String answer = "";
int max = Integer.MIN_VALUE;
String[] s = str.split(" ");
for (String x : s) {
int len = x.length();
if (len > max) {
max = len;
answer = x;
}
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
String str = kb.next();
System.out.println(T.solution("it is time to study"));
}
}
------------------------------------------------------------
// (2) IndexOf(), substring() 사용
public class Main {
public String solution(String str) {
String answer = "";
int max = Integer.MIN_VALUE;
int pos;
while ((pos = str.indexOF('')) != -1) {
String temp = str.substring(0, pos);
int len = temp.length();
if (len > max) {
max = len;
answer = temp;
}
str = str.substring(pos+1);
}
if(str.length() > max) answer = str;
return answer;
}