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

วิธีพิมพ์ตัวอักษรแรกของแต่ละคำใน String ด้วย Java


String ใช้แทนสตริงอักขระ ทุกตัวอักษรในโปรแกรม Java ถูกใช้งานเป็น อินสแตนซ์ของคลาส String String เป็น ค่าคงที่ และค่าไม่สามารถเปลี่ยนแปลงได้ (immutable) หลังสร้างแล้ว

เราสามารถพิมพ์ตัวอักษรแรกของแต่ละคำในสตริงได้โดยโปรแกรมด้านล่าง

ตัวอย่าง

public class FirstCharacterPrintTest {
    public static void main(String[] args) {
        String str = "Welcome To Tutorials Point";
        char c[] = str.toCharArray();
        System.out.println("The first character of each word: ");
        for (int i = 0; i < c.length; i++) {
            // Logic to implement first character of each word in a string
            if (c[i] != ' ' && (i == 0 || c[i-1] == ' ')) {
                System.out.println(c[i]);
            }
        }
    }
}

ผลลัพธ์

The first character of each word: W T T P