ในบทความนี้ เราจะเข้าใจวิธีการลบช่องว่างทั้งหมดออกจากสตริง สตริงเป็นประเภทข้อมูลที่มีอักขระตั้งแต่หนึ่งตัวขึ้นไปและอยู่ในเครื่องหมายคำพูดคู่ (“ ”)
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Input string: Java programming is fun to learn.
ผลลัพธ์ที่ต้องการจะเป็น −
The string after replacing white spaces: Javaprogrammingisfuntolearn.
อัลกอริทึม
Step 1 - START
Step 2 - Declare two strings namely String input_string and result.
Step 3 - Define the values.
Step 4 - Use the function replaceAll("\\s", "") to replaces all the white spaces with blank spaces.
Step 5 - Display the result
Step 6 - Stop ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
public class Demo {
public static void main(String[] args) {
String input_string = "Java programming is fun to learn.";
System.out.println("The string is defined as: " + input_string);
String result = input_string.replaceAll("\\s", "");
System.out.println("\nThe string after replacing white spaces: " + result);
}
} ผลลัพธ์
The string is defined as: Java programming is fun to learn. The string after replacing white spaces: Javaprogrammingisfuntolearn.
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
public class Demo {
public static String string_replace(String input_string){
String result = input_string.replaceAll("\\s", "");
return result;
}
public static void main(String[] args) {
String input_string = "Java programming is fun to learn.";
System.out.println("The string is defined as: " + input_string);
String result = string_replace(input_string);
System.out.println("\nThe string after replacing white spaces: " + result);
}
} ผลลัพธ์
The string is defined as: Java programming is fun to learn. The string after replacing white spaces: Javaprogrammingisfuntolearn.