ในบทความนี้ เราจะเรียนรู้วิธีพิมพ์สตริง (String) ในภาษา Java String เป็นลำดับของตัวอักษรและค่า alphanumeric
วิธีสร้าง String
// String literal (ใช้บ่อยที่สุด)
String str = "Welcome to the club!!!";
// ใช้ new keyword
String str2 = new String("Welcome to the club!!!");
คุณสมบัติสำคัญ
- String เป็น Object ใน Java
- Immutable: สร้างแล้วเปลี่ยนค่าไม่ได้ (การ "เปลี่ยน" จะสร้าง object ใหม่)
- ต้องการแก้ไขเยอะๆ ให้ใช้
StringBuilderหรือStringBuffer
ตัวอย่างการทำงาน
อินพุต:
Hello my name is John!
เอาต์พุต:
The string is: Hello my name is John!
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร String
- รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- แสดงบนคอนโซลด้วย
System.out.println() - จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class PrintString {
public static void main(String[] args) {
String my_str;
System.out.println("The required packages have been imported");
Scanner my_scan = new Scanner(System.in);
System.out.print("A scanner object has been defined \n");
System.out.print("Enter a string: ");
my_str = my_scan.nextLine();
System.out.print("The nextLine method is used to read the string");
System.out.println("The string is: ");
System.out.println(my_str);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class PrintString {
public static void main(String[] args) {
String my_str;
System.out.println("The required packages have been imported");
my_str = "Hello my name is John!";
System.out.println("The string is: ");
System.out.println(my_str);
}
}
เมธอด String ที่ใช้บ่อย
| เมธอด | คำอธิบาย |
|---|---|
| length() | ความยาวสตริง |
| charAt(index) | ตัวอักษรตำแหน่ง index |
| substring(start, end) | ตัดสตริงย่อย |
| toUpperCase() / toLowerCase() | แปลงตัวใหญ่/เล็ก |
| equals(other) | เปรียบเทียบค่า (ไม่ใช่ ==) |
| contains(substr) | ตรวจสอบมี substring หรือไม่ |
| split(regex) | แยกสตริงเป็นอาร์เรย์ |