문자열를 원하는 위치만큼 잘라내고 싶을때가 있을것이다.
java 에 있는 내장함수인 substring을 활용해 보겠다.
문자열 자르기 - substring()
java.lang.String 클래스의 substring() 메소드는
문자열의 특정 부분을 잘라내는 데 사용합니다.
substring() 메소드는 다음과 같이 2가지 형태로 사용할 수 있습니다.
public String substring(int startIndex)
public String substring(int startIndex, int endIndex)
startIndex부터 끝까지의 문자열을 리턴합니다.
public String substring(int startIndex)

그림에 나온것과 같이 substring() 메소드는
substring() 메소드에 파라미터를 1개만 전달(startIndex)하면
문자열의 startIndex부터 끝까지의 문자열을 잘라서 리턴한다.
str.substring(2);
위 그림과 같은 예제입니다.
"Hello" 문자열 index 2부터('l') 마지막까지 문자열을 잘라서 리턴합니다.
str.substring(5);
문자열의 마지막 index + 1 값을 startIndex로 지정하면, 빈 문자열을 리턴합니다.
str.substring(-1);
str.substring(6);
startIndex로 음수값이나, 범위를 벗어나는 값을 입력하면
StringIndexOutOfBoundsException이 발생합니다.
substring(int startIndex, int endIndex)
startIndex(포함)부터 endIndex(불포함)까지의 문자열을 리턴합니다.
public String substring(int startIndex, int endIndex)

위 그림과 같이
substring() 메소드에 2개의 파라미터를 전달하면(startIndex, endIndex)
startIndex부터 endIndex까지의 문자열을 잘라서 리턴합니다.
정확하게는 startIndex부터 lastIndex 전까지의 문자열을 잘라서 리턴합니다.
이제 substring을 이용하여 문제를 한번 풀어보자

백준 열 개씩 끊어 출력하기 문제이다.