SeouliteLab

[Java/자바] 문자열에서 Index로 문자 가져오기 본문

프로그래밍

[Java/자바] 문자열에서 Index로 문자 가져오기

Seoulite Lab 2024. 3. 8. 09:03

예제 1: charAt() 메서드 사용

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Index로 문자 가져오기
        char ch = str.charAt(7);
        
        // 결과 출력
        System.out.println("Index 7에 위치한 문자: " + ch);
    }
}

charAt() 메서드를 사용하여 문자열에서 특정 Index에 위치한 문자를 가져올 수 있습니다.

예제 2: substring() 메서드 사용

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Index로 문자 가져오기
        String substring = str.substring(7, 8);
        
        // 결과 출력
        System.out.println("Index 7에 위치한 문자: " + substring);
    }
}

substring() 메서드를 사용하여 문자열에서 특정 Index 범위에 위치한 문자를 가져올 수 있습니다.

예제 3: toCharArray() 메서드 사용

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // Index로 문자 가져오기
        char[] charArray = str.toCharArray();
        char ch = charArray[7];
        
        // 결과 출력
        System.out.println("Index 7에 위치한 문자: " + ch);
    }
}

toCharArray() 메서드를 사용하여 문자열을 문자 배열로 변환한 후, Index를 통해 문자를 가져올 수 있습니다.