Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมธอด charAt() ใน Java: ดึงตัวอักษรตามตำแหน่ง

เมธอด charAt() คืนค่าตัวอักษรที่ตำแหน่ง index ที่ระบุใน String ตัวแรกมี index 0 คืนค่าเป็น char เดียว

รูปแบบ charAt()

char = stringName.charAt(index)

รับพารามิเตอร์ 1 ตัว: index ของตัวอักษรที่ต้องการ (เริ่มจาก 0)

ตัวอย่าง: ดึงตัวอักษรแรกของชื่อ

public class GetFirstLetter {
    public static void main(String[] args) {
        String name = "GRAHAM HENDERSON";
        char letter = name.charAt(0);
        System.out.println("The first letter of " + name + "'s name is " + letter + ".");
    }
}

ผลลัพธ์: The first letter of GRAHAM HENDERSON's name is G.

ดึงตัวอักษรตัวที่ 2 (index 1)

char letter = name.charAt(1); // ได้ 'R'

ตัวอย่างประยุกต์: นับจำนวนตัวอักษร 'G' ในชื่อ

class GetLetters {
    public static void main(String[] args) {
        String name = "GRAHAM HENDERSON";
        int counter = 0;
        
        for (int i = 0; i <= name.length() - 1; i++) {
            if (name.charAt(i) == 'G') {
                counter++;
            }
        }
        System.out.println(name + "'s name contains " + counter + " G.");
    }
}

ผลลัพธ์: GRAHAM HENDERSON's name contains 1 G.

โค้ดทำงานอย่างไร

  1. วนลูปทุกตัวอักษรใน name (i = 0 ถึง length-1)
  2. ตรวจสอบ name.charAt(i) == 'G' (case-sensitive)
  3. ถ้าเจอ เพิ่ม counter
  4. แสดงผลรวม

สรุป

charAt() ดึงตัวอักษรตาม index ได้แม่นยำ ใช้ร่วมลูปนับหรือค้นหาตัวอักษรได้สะดวก