현재
3.문장 속 단어(Split,substring) 본문
설명
가장 긴 단어 출력(단, 가장 긴 단어의 길이가 같을 시 맨 앞의 단어를 출력한다)
예시 입력 1
it is time to study
예시 출력 1
study
<힌트>
더보기
- split사용
- substring 사용
<풀이코드>
더보기
import java.util.Scanner;
class Main {
public String solution(String str) {
String answer = ""; //출력할 값 저장
// 방법 1
// int lengthOfWord = Integer.MIN_VALUE; // 판별할 길이 초기화 가장작은값 (-2147483648)
// String words[] = str.split(" ");
// for(String word : words){
// if(word.length() > lengthOfWord) {
// lengthOfWord = word.length();
// answer = word;
// }
// }
// 방법 2 substring 사용
int lengthOfWord = Integer.MIN_VALUE, pos;
while ((pos=str.indexOf(' '))!=-1) {
String temp = str.substring(0, pos);
int length = temp.length();
if(length > lengthOfWord){
lengthOfWord = temp.length();
answer = temp;
}
str = str.substring(pos+1); //공백까지 자르고 다시 시작
if(str.length() > length) answer = str;
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner sc = new Scanner(System.in);
String str = sc.nextLine(); //한줄을 입력 받을때는 nextLine
System.out.println(T.solution(str));
sc.close();
}
}
'알고리즘 > 기타알고리즘문제' 카테고리의 다른 글
| 9. 숫자만 추출(Character.isDigit(char)) (1) | 2024.04.01 |
|---|---|
| 4.단어 뒤집기(StringBuilder, reverse, valueOf()) (0) | 2024.03.25 |
| 2. 대소문자 바꾸기(아스키코드, toLowerCase, toUpperCase) (0) | 2024.03.19 |
| 1. 문자 찾기(toCharArray) (0) | 2024.03.19 |
| 체스판 만들기(미완) (0) | 2023.09.18 |