บทนำ
ในบทความนี้ เราจะเรียนรู้วิธีการแทนที่ช่องว่าง (Whitespace) ในสตริง ด้วยตัวอักษรเฉพาะที่กำหนด สตริงเป็นชนิดข้อมูลที่ประกอบด้วยตัวอักษรหนึ่งตัวขึ้นไป และล้อมรอบด้วยเครื่องหมายคำพูดคู่ (" ")
ตัวอย่างการทำงาน
อินพุทตัวอย่าง:
Input string: Java Program is fun to learn Input character: $
เอาต์พุทที่คาดหวัง:
The string after replacing spaces with given character is: Java$Program$is$fun$to$learn
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศสตริงชื่อ input_string และตัวอักษรชื่อ input_character ขั้นตอนที่ 3 - กำหนดค่า ขั้นตอนที่ 4 - ใช้ฟังก์ชัน replace() แทนที่ช่องว่างด้วยตัวอักษรที่กำหนด ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - จบการทำงาน
ตัวอย่างที่ 1: เขียนในฟังก์ชัน main โดยตรง
public class Demo {
public static void main(String[] args) {
String input_string = "Java Program is fun to learn";
System.out.println("The string is defined as: " + input_string);
char input_character = '$';
System.out.println("The character is defined as: " + input_character);
input_string = input_string.replace(' ', input_character);
System.out.println("The string after replacing spaces with given character is: ");
System.out.println(input_string);
}
}
เอาต์พุท
The string is defined as: Java Program is fun to learn The character is defined as: $ The string after replacing spaces with given character is: Java$Program$is$fun$to$learn
ตัวอย่างที่ 2: ใช้เมธอดแยก (Object-Oriented Style)
public class Demo {
static void space_replace(String input_string, char input_character) {
input_string = input_string.replace(' ', input_character);
System.out.println("The string after replacing spaces with given character is: ");
System.out.println(input_string);
}
public static void main(String[] args) {
String input_string = "Java Program is fun to learn";
System.out.println("The string is defined as: " + input_string);
char input_character = '$';
System.out.println("The character is defined as: " + input_character);
space_replace(input_string, input_character);
}
}
เอาต์พุท
The string is defined as: Java Program is fun to learn The character is defined as: $ The string after replacing spaces with given character is: Java$Program$is$fun$to$learn