본문 바로가기
Programming/Java

[Java] 문자열 자르기 (substring)

by 서현 SEOHYEON 2023. 4. 30.

💚 문자열을 자르는 substring

- 문자열을 원하는 구간만큼 잘라야 하는 경우가 있다. 이때 사용하는 것이 String 클래스의 substring 메서드이다.

 

- substring은 두 종류가 있다.

① substring(int beginIndex)

beginIndex부터(포함해서) 문자열의 끝까지 자른다.

② substring(int beginIndex, int endIndex)

beginIndex부터(포함해서) endIndex 전까지 자른다.

ex) endIndex가 5라면 index 4까지만 자른다.

 

 

💚 substring 예시

public class substringTest {

    public static void main(String[] args) {
        String str1 = "Hello, World!";
        String str2 = str1.substring(7);
        String str3 = str1.substring(0, 5);

        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }

}

- 출력 결과

Hello, World!
World!
Hello

 

Hello와 World 사이의 ','가 5번 인덱스, 공백이 6번 인덱스임을 참고.

 


공식 docs

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

 

String (Java Platform SE 8 )

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argum

docs.oracle.com

 

댓글