java.lang 패키지의 String 클래스는 문자들의 집합을 표현합니다. 자바 프로그램에 등장하는 모든 문자열 리터럴(예: "abc")은 이 클래스의 인스턴스로 구현됩니다. 여기서 문자열 인덱스란 0부터 시작하여 문자열 내 각 문자의 위치를 나타내는 정수를 의미합니다.
부분문자열(substring)이란 하나의 문자열을 이루는 일부 구간을 뜻합니다. String 클래스의 substring() 메서드를 사용하면 문자열에서 원하는 부분을 손쉽게 잘라낼 수 있으며, 이 메서드는 다음과 같이 두 가지 형태로 제공됩니다.
1. substring(int beginIndex) – 시작 인덱스만 지정
이 메서드는 현재 문자열의 인덱스를 나타내는 정수 값을 하나 받아, 해당 인덱스 위치부터 문자열 끝까지의 부분문자열을 반환합니다. 지정한 인덱스가 음수이거나 문자열 길이보다 크면 StringIndexOutOfBoundsException이 발생하므로 주의해야 합니다.
예제
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Enter the index of the substring: ");
int index = sc.nextInt();
String res = str.substring(index);
System.out.println("substring = " + res);
}
}
실행 결과
Enter a string: Welcome to Tutorialspoint Enter the index of the substring: 11 substring = Tutorialspoint
"Welcome to Tutorialspoint"에서 인덱스 11은 문자 'T'에 해당합니다. 따라서 11번째 문자부터 문자열 끝까지인 "Tutorialspoint"가 출력됩니다.
2. substring(int beginIndex, int endIndex) – 시작과 끝 인덱스 지정
이 메서드는 시작 인덱스와 끝 인덱스에 해당하는 두 개의 정수 값을 받아, 두 인덱스 사이의 부분문자열을 반환합니다. 중요한 점은 시작 인덱스의 문자는 결과에 포함되지만, 끝 인덱스의 문자는 포함되지 않는다는 것입니다(시작 인덱스는 포함, 끝 인덱스는 제외).
예제
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Enter the start index of the substring: ");
int start = sc.nextInt();
System.out.println("Enter the end index of the substring: ");
int end = sc.nextInt();
String res = str.substring(start, end);
System.out.println("substring = " + res);
}
}
실행 결과
Enter a string: hello how are you welcome to Tutorialspoint Enter the start index of the substring: 10 Enter the end index of the substring: 20 substring = are you we
위 예제에서는 인덱스 10부터 19까지(끝 인덱스 20은 제외)의 문자들이 잘려나가 "are you we"가 출력된 것을 확인할 수 있습니다.
마무리 정리
substring() 메서드는 인수를 하나만 전달하면 해당 위치부터 문자열 끝까지를 반환하고, 인수를 두 개 전달하면 시작 인덱스(포함)부터 끝 인덱스(제외) 직전까지의 문자열을 반환합니다. 인덱스가 문자열 범위를 벗어나면 예외가 발생하므로, 항상 str.length()로 문자열 길이를 확인한 후 안전하게 인덱스를 지정하는 것이 좋습니다.