본문 바로가기
백엔드개발자/알고리즘관련

가장 긴 단어 출력 / java split(), indexOf(), substring()

by 보혀니 2021. 10. 6.

//
// 한개의 문장이 주어지면 그 문장 속에서 가장 긴 단어를 출력하는 프로그램 작성

// 문장속 단어는 공백으로 구분된다.
// 문장은 영어 알파벳으로 구성되어있다. 

// 가장 길이가 긴 단어가 여러개일 경우 문장속에서 가장 앞에 위치한 단어를 답으로 한다.
//

 

 

import java.util.Scanner;

public class Main {

	public String solution(String str) {
		String answer = "";
		int m = Integer.MIN_VALUE;
		String[] s = str.split(" ");
		for (String x : s) {
			int len = x.length();
			if (len > m) {
				m = len;
				answer = x;
			}
		}
		return answer;
	}

	public String solution2(String str) {
		String answer2 = "";

		int m2 = Integer.MIN_VALUE, pos;
//		int m2, pos;
//		m2 = Integer.MIN_VALUE;
//		m2만 초기화 해준 것임
//		뭔가했네 아 ㅡㅡ

		while ((pos = str.indexOf(' ')) != -1) {
			String tmp = str.substring(0, pos);
			int len = tmp.length();
			if (len > m2) {
				m2 = len;
				answer2 = tmp;
			}
		}
		str = str.substring(pos + 1);
		if (str.length() > m2) {
			answer2 = str;
		}
		return answer2;
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str = kb.nextLine();
		System.out.print("솔루션1 :" + T.solution(str));
		System.out.print("솔루션2 :" + T.solution2(str));
	}

}

 

 

 

 

 

 

 

 

split()

split => 매개변수가 1개, 2개인 split이 있다.

public String[] split(String regex);

=> 문자열을 regex(정규식)에 맞춰서 분리

public String[] split(String regex, int limit);

=> 위와 같음 , 그리고 limit 만큼 문자열 분리

		String st = "1 22 333 4444";
		String[] arry = st.split(" ");
		for (String x : arry) {
			System.out.println(x);
		}
		
		System.out.println("*****");
        
		String[] arry2 = st.split(" ",2);
		for(String y : arry2) {
			System.out.println(y);
		}

결과

 

 

 메타문자를 구분자로 사용하는 경우

		String st = "1.22.333.4444";
		String[] arry = st.split("\\.");
		for (String x : arry) {
			System.out.println(x);
		}

역슬래쉬 두개 붙여야함~

 

결과

 

메타문자의 종류

  • ^ : 문자열의 처음을 나타낸다.
  • $ : 문자열의 끝을 나타낸다.
  • . : 임의의 한 문자를 나타낸다.
  • * : 바로 앞의 문자가 없거나 하나 이상이다.
  • + : 바로 앞의 문자가 하나 이상이다.
  • ? : 앞의 문자가 없거나 하나이다.
  • [ ] : 한 문자를 가리키고 묶음 안의 내용은 가리키는 문자의 범위를 나타낸다.
  • { } : 앞에 있는 문자의 개수를 나타내고 묶음 안에서 ','는 문자 개수의 범위를 나타낼 때 쓴다.
  • ( ) : 괄호 안의 문자열은 하나로 묶어 취급한다.
  • | : 또는(or)의 뜻으로 선택문에 쓰인다.
  • \ : 메타 문자의 성질을 없앨 때 붙인다.

(메타문자의 종류 출처 : https://jsj0903.tistory.com/7 )

 

 

 

 

 

 

 

indexOf()

 

  indexOf(String str)

  indexOf(int ch)

  indexOf(int ch, int fromIndex)

  indexOf(String str, int fromIndex)

 

=> 특정문자나 문자열이 앞에서부터 처음 발견되는 인덱스를 반환함

   만약 찾지 못했을 때에는 -1 을 반환한다.

 

출처: https://mine-it-record.tistory.com/124

 

 

public class IndexOf {
	public static void main(String[] args) {
		String indexOfTest = "Hello world2";
		System.out.println(indexOfTest.indexOf("2"));
		
		System.out.println(indexOfTest.indexOf("o",5));
//		o의 첫번째 index는  4에 있지만
//		시작할 위치를 5로 했기 때문에 world에있는 o 인덱스가 나옴
		
		
		System.out.println(indexOfTest.indexOf("k"));
	}
}

 

결과

lastIndexOf()

indexOf() 와 같은데 뒤에서부터 시작해서 찾음

근데 반환하는 index는 위와 같음.

public class Exx {
	public static void main(String[] args) {
		String indexOfTest = "Hello world";
		System.out.println(indexOfTest.lastIndexOf("o"));
	}
}

  결좌는 7 이 나온다.

 

 

 

 

substring()

public class SubstringTest {
	public static void main(String[] args) {
		String str = "아침부터 너무 잠온다";
		System.out.println(str.substring(0));
		System.out.println(str.substring(3));
		System.out.println(str.substring(3,8));
	}
}
   
0 1 2 3 4 5 6 7 8 9

결과