[Java] 문자열 자르기 substring() 사용방법

박수민·2024년 7월 31일

substring() 메소드를 사용하여 문자열을 자르는 방법을 소개하려고 합니다.

substring()

  • java.lang.String 클래스의 substring() 메소드는 문자열의 특정 부분을 잘라내는 데 사용합니다.
  • substring() 메소드는 다음과 같이 2가지 형태로 사용할 수 있습니다.
    • public String substring(int startIndex)
    • public String substring(int startIndex, int endIndex)

substring(int startIndex)

  • startIndex부터 끝까지의 문자열을 리턴합니다.
  • substring() 메소드에 파라미터를 1개만 전달(startIndex)하면 문자열의 startIndex부터 끝까지의 문자열을 잘라서 리턴합니다. (index는 0부터 시작합니다.)
public class SubstringExample {
	public static void main(String[] args) {
    
    	String str = "Programmers";
     
     	System.out.println(str.substring(2)); // "ogrammers"
        System.out.println(str.substring(5)); // "ammers"
        System.out.println(str.substring(11)); // ""
        System.out.println(str.substring(-1)); // StringIndexOutOfBoundsException
        System.out.println(str.substring(12)); // StringIndexOutOfBoundsException
        
 	}
}

substring(int startIndex, int endIndex) 

  • startIndex(포함)부터 endIndex(불포함)까지의 문자열을 리턴합니다.
  • substring() 메소드에 2개의 파라미터를 전달하면(startIndex, endIndex) startIndex부터 endIndex까지의 문자열을 잘라서 리턴합니다.
    • 정확하게는 startIndex부터 lastIndex 전까지의 문자열을 잘라서 리턴합니다.
public class SubstringExample {
	public static void main(String[] args) {
    
    	String str = "Programmers";
     
     	System.out.println(str.substring(2, 6)); // "ogra"
        System.out.println(str.substring(2, str.length())); // "ogrammers"
        
 	}
}

0개의 댓글