서버&백엔드/🔥 JAVA

JAVA | 문자열 슬라이싱

이재원 2024. 11. 3. 14:50

1. substring()

substring() 메서드는 문자열의 특정 부분을 추출합니다. 두 가지 오버로드된 형태가 있습니다.

  • 시작인덱스 하나만 제공 : 시작 인덱스부터 끝까지 부분 문자열을 반환합니다.
String str = "Hello, World!";
//            0123456789...
String sub1 = str.substring(7); // "World!"
  • 시작 인덱스와 종료 인덱스 제공: 시작 인덱스 부터 종료 인덱스 전까지의 부분 문자열을 반환합니다.
String sub2 = str.substring(0, 5); // "Hello"

 

2.split()

split() 메서드는 주어진 구분자를 기준으로 문자열을 나누어 배열로 반환합니다.

String str = "apple,banana,orange";
String[] fruits = str.split(","); // ["apple", "banana", "orange"]
String str = "apple";
String[] characters = str.split(""); // ["", "a", "p", "p", "l", "e"]

 

3. charAt()

charAt() 메서드는 주어진 인덱스에 있는 단일 문자를 반환합니다.

String str = "Hello";
char ch = str.charAt(1); // 'e'

 

4. indexOf()

indexOf() 메서드는 특정 문자열이 처음 나타나는 위치(인덱스)를 반환합니다. 문자열이 없으면 -1을 반환합니다.

String str = "Hello, World!";
int index = str.indexOf("World"); // 7

 

5. lastIndexOf()

lastIndexOf() 메서드는 특정 문자열이 마지막으로 나타나는 위치(인덱스)를 반환합니다.

String str = "Hello, World! Hello again!";
int lastIndex = str.lastIndexOf("Hello"); // 19

 

6. replace()

replace() 메서드는 주어진 문자열의 특정 부분을 다른 문자열로 대체합니다. 슬라이싱의 직접적인 방법은 아니지만, 문자열을 변경하는 데 유용합니다.

String str = "Hello, World!";
String newStr = str.replace("World", "Java"); // "Hello, Java!"

 

7. trim()

trim() 메서드는 문자열의 시작과 끝에 있는 공백을 제거합니다. 슬라이싱의 일환으로 사용될 수 있습니다.

String str = "   Hello, World!   ";
String trimmedStr = str.trim(); // "Hello, World!"

 

8. getBytes()

getBytes() 메서드는 문자열을 바이트 배열로 변환합니다. 특정 부분을 슬라이싱 하기 위해 사용될 수 있습니다.

String str = "Hello";
byte[] bytes = str.getBytes(); // [72, 101, 108, 108, 111]

 

9. toCharArray()

toCharArray() 메서드는 문자열을 문자 배열로 변환합니다. 각 문자를 개별적으로 처리할 수 있습니다.

String str = "Hello";
char[] charArray = str.toCharArray(); // ['H', 'e', 'l', 'l', 'o']

 

예제

다음은 다양한 슬라이싱 메서드를 사용하는 예제입니다.

public class StringSlicingExample {
    public static void main(String[] args) {
        String str = "Hello, World!";

        // substring 예제
        String subStr1 = str.substring(7); // "World!"
        String subStr2 = str.substring(0, 5); // "Hello"

        // split 예제
        String csv = "apple,banana,orange";
        String[] fruits = csv.split(",");

        // charAt 예제
        char firstChar = str.charAt(0); // 'H'

        // indexOf 예제
        int index = str.indexOf("World"); // 7

        // lastIndexOf 예제
        int lastIndex = str.lastIndexOf("l"); // 9

        // replace 예제
        String replacedStr = str.replace("World", "Java"); // "Hello, Java!"

        // trim 예제
        String trimmedStr = "   Hello, World!   ".trim(); // "Hello, World!"

        // 결과 출력
        System.out.println("Substring from index 7: " + subStr1);
        System.out.println("Substring from index 0 to 5: " + subStr2);
        System.out.println("Fruits: " + String.join(", ", fruits));
        System.out.println("First character: " + firstChar);
        System.out.println("Index of 'World': " + index);
        System.out.println("Last index of 'l': " + lastIndex);
        System.out.println("Replaced string: " + replacedStr);
        System.out.println("Trimmed string: " + trimmedStr);
    }
}
반응형