Đếm số từ trong TextView Android
Hướng dẫn này minh họa cách đếm số từ trong một đoạn văn bản hiển thị trên TextView và hiển thị kết quả qua Toast.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: Code logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
// Văn bản mẫu (Lorem Ipsum)
String paragraph = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. " +
"Lorem Ipsum has been the industry's standard dummy text ever since the " +
"1500s, when an unknown printer took a galley of type and scrambled it to " +
"make a type specimen book. It has survived not only five centuries, but " +
"also the leap into electronic typesetting, remaining essentially unchanged. " +
"It was popularised in the 1960s with the release of Letraset sheets " +
"containing Lorem Ipsum passages, and more recently with desktop publishing " +
"software like Aldus PageMaker including versions of Lorem Ipsum.";
text.setText(paragraph);
// Tách từ bằng regex \\s+ (khớp 1 hoặc nhiều khoảng trắng)
String[] words = text.getText().toString().split("\\s+");
// Hiển thị số từ qua Toast
Toast.makeText(MainActivity.this, "Số từ: " + words.length, Toast.LENGTH_LONG).show();
}
}
Giải thích Regex \\s+
\\s: Khớp mọi ký tự khoảng trắng (space, tab, newline).+: Khớp 1 hoặc nhiều lần.- Giúp xử lý đúng khi có nhiều khoảng trắng liên tiếp hoặc xuống dòng.
Cải tiến: Đếm từ chính xác hơn
// Loại bỏ dấu câu trước khi đếm
String cleanText = text.getText().toString().replaceAll("[^\\p{L}\\p{N}\\s]", "");
String[] words = cleanText.trim().split("\\s+");
Chạy ứng dụng
App hiển thị văn bản Lorem Ipsum, Toast hiện ra số từ (khoảng 69 từ).
