String

20 August 2016

ในบทนี้ คุณจะได้เรียนเกี่ยวกับประเภทข้อมูล String และคลาสของ String โดยละเอียด และนอกจากนี้ยังเรียนรู้ถึงวิธีการใช้เมธอดเพื่อจัดการ String ในภาษา Java

การประกาศ String

String เป็นข้อมูลประเภทออบเจ็คและในการประกาศตัวแปรนั้นทำได้โดยคลาส String ในภาษา Java นั้นมีคลาส String เพื่อช่วยในการจัดการกับข้อมูลที่เป็นข้อความที่ต่อเนื่องกัน String นั้นแตกต่างจากตัวอักษรหรือข้อมูลแบบ char ซึ่งเก็บข้อมูลได้เพียงตัวเดียว นอกจากนี้ String ยังมีเมธอดสำหรับจัดการข้อมูลเพื่ออำนวยสะดวกสำหรับนักพัฒนาโปรแกรม มาดูตัวอย่างการประกาศ String ในภาษา Java

// method 1
String str = "Declaring string in Java.";
// method 2
String str2 = new String("Creating with String constructor.");
// method 3
char[] chs = new char[] {'C', 'h', 'a', 'r',  'a', 'r', 'r', 'a', 'y'};
String str3 = new String(chs);

ในตัวอย่าง เราสามารถประกาศตัวแปร String ได้ 3 วิธี วิธีแรกเป็นวิธีปกติที่เราได้ใช้มาก่อนหน้าแล้ว มันสะดวกและใช้งานง่ายที่สุดโดยกำหนดค่าของ String ให้กับตัวแปรโดย String literal นั้นจะอยู่ในเครื่องหมาย Double quote วิธีที่สองเป็นการประกาศ String ผ่าน Constructor ของคลาส และวิธีสุดท้ายเป็นการประกาศ String ด้วย Char array ผ่าน Constructor เช่นกัน คุณสามารถประกาศโดยวิธีใดก็ได้ ซึ่งได้ผลลัพธ์ที่ไม่แตกต่างกัน

String Concatenation (+)

เราได้พูดเกี่ยวกับการดำเนินการกับ String แล้วในบทของตัวดำเนินการ String Concatenation นั้นเป็นการนำ String ตั้งแต่หนึ่งหรือหลายอันมาต่อกัน โดยการใช้เครื่องหมายบวก (+) จะได้ String และเนื่องจาก String นั้นเป็นคลาส การใช้เครื่องหมาย + กับ String จึงเป็นการ Overloading operator

String firstName = "Bob";
String lastName = "Henry";

String fullName = firstName + " " + lastName;

ในตัวอย่าง เราได้ทำการต่อ 3 String เข้าด้วยกัน และนำค่าที่ได้จากการต่อใส่ตัวแปรใหม่ fullName ผลลัพธ์ที่ได้คือมันจะมีค่าเป็น "Bob Henry" ที่เกิดจากการเชื่อมต่อกันของ String ทั้งสาม

มาดูตัวอย่างเพิ่มเติมเกี่ยวกับการใช้งาน String ภาษา Java ซึ่งเป็นโปรแกรมถามผู้ใช้ให้กรอกชื่อ อายุ และกีฬาโปรดของเขา

import java.util.Scanner;

public class Constant {    

    public static void main(String[] args)
    {
        String name;
        int age;
        String sport;

        Scanner reader = new Scanner(System.in);
        Scanner reader2 = new Scanner(System.in);

        System.out.print("What's your name?: ");
        name = reader.nextLine();

        System.out.print("How old are you?: ");
        age = reader2.nextInt();

        System.out.print("What's your favorite sport?: ");
        sport = reader.nextLine();

        System.out.println("Hello " + name);
        System.out.print("You was born in " + (2017 - age));
        System.out.println(" and loves to play " + sport);
    }

}

ในตัวอย่าง เป็นโปรแกรมในการถามข้อมูลของผู้ใช้และแสดงข้อมูลเหล่านั้นด้วยการต่อ String ในตอนแรกของโปรแกรม เราได้ประกาศตัวแปร name สำหรับเก็บชื่อ age สำหรับเก็บอายุ และ sport สำหรับเก็บกีฬาโปรด

Scanner reader = new Scanner(System.in);
Scanner reader2 = new Scanner(System.in);

ต่อมาเราได้ประกาศออบเจ็คจากคลาส Scanner สำหรับอ่านรับค่าทางคีย์บอร์ด โดยตัวแปร reader ใช้สำหรับรับค่าที่เป็น String และตัวแปร reader2 จะใช้สำหรับค่าที่เป็นตัวเลข เราจะเป็นต้องแยกเพื่อให้โปรแกรมสามารถจัดการกับข้อมูลใน Stream ได้ถูกต้องในตอนรับค่า

System.out.print("What's your name?: ");
name = reader.nextLine();

System.out.print("How old are you?: ");
age = reader2.nextInt();

System.out.print("What's your favorite sport?: ");
sport = reader.nextLine();

เราได้แสดงข้อความเพื่อถามผู้ใช้สำหรับการรับค่าชื่อ อายุ และกีฬาโปรด ตามลำดับ

System.out.println("Hello " + name);
System.out.print("You was born in " + (2016 - age));
System.out.println(" and loves to play " + sport);

นี่เป็นการต่อ String ในพื้นฐาน ในคำสั่งแรกเราได้แสดงคำทักทายผู้ใช้โดยการต่อคำทักทายและชื่อของเขาเข้าด้วยกัน ในคำสั่งที่สอง เราได้คำนวณหาปีที่เกิดโดยการนำอายุไปลบกับ 2016 ในคำสั่งนี้เป็นการต่อ String กับข้อมูลประเภท Integer ซึ่งจะทำให้ Literal ของ Integer นั้นถูกแปลงเป็น String ซึ่งหลักการนี้สามารถเกิดขึ้นได้เมื่อคุณนำ String ไปต่อกับประเภทข้อมูลชนิดอื่น ซึ่งจะได้เป็น Literal ของข้อมูลชนิดนั้นในรูปแบบของ String และคำสั่งสุดท้ายเป็นการแสดงถึงกีฬาโปรด

What's your name?: John
How old are you?: 28
What's your favorite sport?: Hockey
Hello John
You was born in 1988 and loves to play Hockey

และนี่เป็นตัวอย่างผลลัพธ์ของโปรแกรมในการต่อ String ในภาษา Java ซึ่งเราได้กรอกชื่อ อายุ และกีฬา เป็น John 28 และ Hockey ตามลำดับ

เมธอดใน String

เพราะว่า String นั้นเป็นคลาส ดังนั้นมันจึงมีเมธอดต่างๆ ที่ให้เราสามารถใช้งานได้ เมธอดก็คือฟังก์ชันที่ใช้ในการจัดการข้อมูล เพื่อให้ได้ผลลัพธ์ออกมาตามหน้าที่ของมัน คุณจะได้เรียนเกี่ยวกับเมธอดในบทต่อไป มาดูตัวอย่างการใช้เมธอดที่สำคัญของ String

public class StringMethod {
    public static void main(String[] args) {   
        String name = "MarcusCode";

        System.out.println("Length is " + name.length());
        System.out.println("Char at index 6 is " + name.charAt(6));

        if (name.contains("Code")) {
            System.out.println("'Code' is in '" + name + "'");
        } else {
            System.out.println("'Code is not in '" + name + "'");
        }

        System.out.println("Index of 'cus' is at " + name.indexOf("cus"));
        name = name.concat(" tutorials");

        System.out.println(name);

        name = name.replace(" tutorials",  "'s Programming");
        System.out.println(name);

        name = name.toUpperCase();
        System.out.println(name);

        name = "";

        if (name.isEmpty()) {
            System.out.println("name is empty.");
        }
    }
}

ข้างบนเป็นโค้ดของการใช้เมธอดในคลาส String เราได้หาความยาวของมัน ดูตัวอักษรที่ตำแหน่ง index 6 ตรวจสอบว่ามี String ย่อยอยู่ข้างในหรือไม่ และตรวจสอบ index ของ cus ที่อยู่ภายใน String เชื่อมต่อ String ใหม่ tutorials เข้ามา แล้วแทนที่ด้วย Programming หลังจากนั้นแปลงให้เป็นตัวพิมพ์ใหญ่ทั้งหมด และกำหนดให้ String ว่างและตรวจสอบในตอนท้าย

Length is 10
Char at index 6 is C
'Code' is in 'MarcusCode'
Index of 'cus' is at 3
MarcusCode tutorials
MarcusCode's Programming
MARCUSCODE'S PROGRAMMING
name is empty.

และนี่เป็นผลลัพธ์จากการใช้งานเมธอดของ String

อย่างไรก็ตาม ภาษา Java นั้นยังมีเมธอดให้ใช้อีกมากมาย ข้างล่างนี้เป็นตารางเมธอดของ String ในภาษา Java

TypeMethodDescription
charcharAt(int index)Returns the char value at index.
intcompareTo(String anotherString)Compares two strings.
Stringconcat(String str)Concatenates the string to the end.
booleancontains(CharSequence s)Returns true if this string contains the specified sequence.
booleanendsWith(String suffix)Tests if this string ends with suffix.
booleanequals(Object anObject)Compares this string to the specified object.
static Stringformat(String format, Object... args)Returns a formatted string.
byte[]getBytes()Encodes this String into a sequence of bytes.
intindexOf(String str)Returns the index within this string of the first occurrence substring.
booleanisEmpty()Returns true if, and only if, length() is 0.
intlength()Returns the length of this string.
booleanmatches(String regex)Tells whether or not this string matches regular expression.
Stringreplace(CharSequence target, CharSequence replacement)Replaces each substring.
String[]split(String regex)Splits this string around matches.
booleanstartsWith(String prefix)Tests if this string starts with the prefix.
Stringsubstring(int beginIndex, int endIndex)Returns a new string that is a substring.
char[]toCharArray()Converts this string to a new character array.
StringtoLowerCase()Converts all of the characters in this String to lower case.
StringtoString()This object is itself returned.
StringtoUpperCase()Converts all of the characters in this String to upper case.
Stringtrim()Returns a copy of the string.
static StringvalueOf(boolean b)Returns the string representation of the boolean argument.
static StringvalueOf(char c)Returns the string representation of the char argument.
static StringvalueOf(double d)Returns the string representation of the double argument.
static StringvalueOf(float f)Returns the string representation of the float argument.
static StringvalueOf(int i)Returns the string representation of the int argument.
static StringvalueOf(long l)Returns the string representation of the long argument.
static StringvalueOf(Object obj)Returns the string representation of the Object argument.

สำหรับเมธอดของ String ทั้งหมดคุณสามารถดูได้ที่นี่ https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

ในบทนี้ คุณได้รู้จักกับ String และทราบว่ามันเป็นอ็อบเจ็คชนิดหนึ่ง และนอกจากนี้ใช้เมธอดต่างๆ ให้ใช้งานในการจัดการ String บทต่อไปเราจะเรียนรู้เกี่ยวกับเมธอด

บทความนี้เป็นประโยชน์หรือไม่? Yes · No