String มีความยาวเท่าไร?
ข้อความมีขนาดหลากหลาย ตั้งแต่อักขระเดียวไปจนถึงทั้งย่อหน้า การรู้จำนวนอักขระใน String มีความสำคัญมากสำหรับการตรวจสอบ การจัดรูปแบบ และการประมวลผลข้อความ มาดูกันว่า Java ช่วยให้วัดความยาวของ String ได้อย่างไร
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Java เบื้องต้น
คำแนะนำการฝึกหัด
- ใช้เมธอด
.length()เพื่อหาความยาวของตัวแปรbookNameแล้วบันทึกผลลัพธ์ไว้ในตัวแปรชื่อbookNameLength - หาความยาวของชื่อผู้แต่ง
"Terry Pratchett"แล้วบันทึกค่าโดยใช้ชนิดข้อมูลพื้นฐานที่เหมาะสม
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class HowLong {
public static void main(String[] args) {
String bookName = "Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch";
// Find the length of bookName
int bookNameLength = bookName.____();
// Find the length of the String and save it
____ authorNameLength = "Terry Pratchett".____;
System.out.println("The length of the book title is " + bookNameLength);
System.out.println("The length of the author's name is " + authorNameLength);
}
}