Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java lấy ký tự từ chuỗi cho trước

Giới thiệu

Trong bài viết này, chúng ta sẽ tìm hiểu cách lấy một ký tự từ chuỗi cho trước. char là kiểu dữ liệu chứa chữ cái, số hoặc ký tự đặc biệt. Chuỗi chứa một hoặc nhiều ký tự, được đặt trong dấu ngoặc kép (" ").

Minh họa

Đầu vào:

Input string: Java Programming Index: 11

Đầu ra mong muốn:

Result: m

Thuật toán

  1. Bắt đầu
  2. Khai báo: chuỗi input_string, ký tự resultant_character
  3. Khởi tạo giá trị
  4. Dùng hàm string.charAt() để lấy ký tự tại vị trí chỉ định, lưu vào resultant_character
  5. Hiển thị kết quả
  6. Kết thúc

Ví dụ 1: Triển khai trong hàm main

public class CharacterAndString {
    public static void main(String[] args) {
        String string = "Java Programming";
        System.out.println("The string is defined as " + string);
        
        int index = 11;
        char resultant_character = string.charAt(index);
        
        System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
    }
}

Đầu ra

The string is defined as Java Programming
A character from the string :Java Programming at index 11 is: m

Ví dụ 2: Tách hàm static

public class CharacterAndString {
    public static char get_chararacter(String string, int index) {
        return string.charAt(index);
    }
    
    public static void main(String[] args) {
        String string = "Java Programming";
        System.out.println("The string is defined as " + string);
        
        int index = 11;
        char resultant_character = get_chararacter(string, index);
        
        System.out.println("\nA character from the string :" + string + " at index " + index + " is: " + resultant_character);
    }
}

Đầu ra

The string is defined as Java Programming
A character from the string :Java Programming at index 11 is: m