Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีลบช่องว่างใน TextView บน Android

การลบช่องว่าง (Whitespace) ใน TextView บน Android

ตัวอย่างนี้สาธิตวิการนำข้อความจาก EditText มาแสดงใน TextView หลังจากลบช่องว่างทั้งหมดออกแล้ว โดยใช้ Regular Expression

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio ตามปกติ

ขั้นตอนที่ 2: ออกแบบ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ป้อนชื่อ (มีช่องว่าง)"
        android:inputType="text" />

    <Button
        android:id="@+id/btnProcess"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="ลบช่องว่างและแสดง" />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:textSize="18sp"
        android:textStyle="bold"
        android:gravity="center" />
</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private EditText etName;
    private TextView tvResult;
    private Button btnProcess;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etName = findViewById(R.id.etName);
        tvResult = findViewById(R.id.tvResult);
        btnProcess = findViewById(R.id.btnProcess);

        btnProcess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = etName.getText().toString();
                if (!input.isEmpty()) {
                    // ใช้ regex \\s+ เพื่อจับช่องว่างทุกประเภท (space, tab, newline) และแทนที่ด้วย empty string
                    String result = input.replaceAll("\\s+", "");
                    tvResult.setText(result);
                    Toast.makeText(MainActivity.this, "ประมวลผลเสร็จสิ้น", Toast.LENGTH_SHORT).show();
                } else {
                    etName.setError("กรุณาป้อนข้อความ");
                }
            }
        });
    }
}

คำอธิบายโค้ดสำคัญ

String result = input.replaceAll("\\s+", "");
  • \\s : ตัวแทนของ whitespace character ทุกประเภท (space, tab \\t, newline \\n, carriage return \\r, form feed \\f)
  • + : หมายถึง one or more (หนึ่งขึ้นไป) จะจับช่องว่างติดกันหลายตัวเป็นกลุ่มเดียว
  • replaceAll : แทนที่ทุกส่วนที่ตรงกับ pattern ด้วย string ที่สอง (ในที่นี้คือ empty string "")

ตัวอย่างผลลัพธ์

Input (EditText)Output (TextView)
"S a i r a m""Sairam"
"Hello\tWorld\nAndroid""HelloWorldAndroid"
" Trim Me ""TrimMe"

กรณีศึกษาเพิ่มเติม

หากต้องการลบเฉพาะช่องว่างนำหน้าและท้าย (trim) แต่เก็บช่องว่างระหว่างคำไว้ ให้ใช้:

String trimmed = input.trim(); // ลบเฉพาะหน้า-หลัง

หรือลบช่องว่างซ้ำเหลือเพียงช่องเดียว:

String singleSpace = input.trim().replaceAll("\\s+", " ");