Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách xóa tất cả nguyên âm từ chuỗi TextView Android

Giới thiệu

Ví dụ này minh họa cách loại bỏ tất cả các nguyên âm (a, e, i, o, u - cả chữ hoa và thường) từ chuỗi nhập vào EditText và hiển thị kết quả lên TextView.

Bước 1: Tạo dự án mới

Android Studio → File → New Project → điền thông tin.

Bước 2: Giao diện (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">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:hint="Nhập tên"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button android:id="@+id/save" android:text="Lưu"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />

    </LinearLayout>

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText name;
    TextView textview;

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

        name = findViewById(R.id.name);
        textview = findViewById(R.id.textview);

        findViewById(R.id.save).setOnClickListener(v -> {
            String input = name.getText().toString();
            if (!input.isEmpty()) {
                // Regex [AEIOUaeiou] khớp tất cả nguyên âm hoa và thường
                String result = input.replaceAll("[AEIOUaeiou]", "");
                textview.setText(result);
                Toast.makeText(this, "Đã xử lý", Toast.LENGTH_LONG).show();
            } else {
                name.setError("Nhập tên");
            }
        });
    }
}

Giải thích Regex

  • [AEIOUaeiou]: Character class khớp với bất kỳ ký tự nào trong tập hợp (nguyên âm hoa và thường).
  • replaceAll(): Thay thế tất cả các lần xuất hiện khớp với chuỗi rỗng "".

Chạy ứng dụng

Cách xóa tất cả nguyên âm từ chuỗi TextView Android

Ví dụ: Nhập "Hello World" → Kết quả "Hll Wrld".