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

วิธีใช้ charAt() ใน TextView Android ดึงตัวอักษรตามตำแหน่ง

ภาพรวม

บทความนี้สาธิตการใช้ String.charAt(int index) เพื่อดึงตัวอักษรที่ตำแหน่งเฉพาะ (Index-based) จากข้อความใน EditText

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 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:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ป้อนข้อความ (อย่างน้อย 6 ตัวอักษร)" />

    <Button
        android:id="@+id/click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="ดึงตัวอักษรที่ 5" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textSize="25sp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (java/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 androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText nameEditText;
    private Button charAtButton;
    private TextView resultTextView;

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

        nameEditText = findViewById(R.id.name);
        charAtButton = findViewById(R.id.click);
        resultTextView = findViewById(R.id.textview);

        charAtButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = nameEditText.getText().toString();

                if (input.isEmpty()) {
                    nameEditText.setError("กรุณาป้อนข้อความ");
                    return;
                }

                int index = 5; // ตำแหน่งที่ 6 (0-based index)

                if (input.length() > index) {
                    char ch = input.charAt(index);
                    resultTextView.setText("ตัวอักษรที่ " + (index + 1) + " (index " + index + "): '" + ch + "'");
                } else {
                    resultTextView.setText("ข้อความสั้นเกินไป ต้องมีอย่างน้อย " + (index + 1) + " ตัวอักษร");
                }
            }
        });
    }
}

คำอธิบาย charAt()

  • Index เริ่มจาก 0 (ตัวแรก = index 0)
  • คืนค่า char (primitive type)
  • Throw IndexOutOfBoundsException ถ้า index < 0 หรือ >= length()
  • คืนค่า UTF-16 code unit (สำหรับ Emoji/ตัวอักษรพิเศษอาจเป็น Surrogate Pair)

ตัวอย่าง

String s = "Hello";
s.charAt(0)  // 'H'
s.charAt(1)  // 'e'
s.charAt(4)  // 'o'
s.charAt(5)  // IndexOutOfBoundsException

จัดการ Unicode/Emoji (Code Points)

String emoji = "😀😁😂"; // แต่ละตัว = 2 chars (Surrogate Pair)

// ใช้ codePointAt แทน
int codePoint = emoji.codePointAt(0); // 0x1F600 (😀)
String charStr = new String(Character.toChars(codePoint)); // "😀"

// นับจริง: ใช้ codePointCount
int count = emoji.codePointCount(0, emoji.length()); // 3

Kotlin

val ch = input.getOrNull(5) ?: ' ' // Safe access, คืน null ถ้าเกิน
val ch = input[5] // Throw exception ถ้าเกิน

ทดสอบ

ป้อน "Hello World" → ตัวอักษรที่ 6 (index 5) = ' ' (Space)
ป้อน "Android" → ตัวอักษรที่ 6 = 'i'
ป้อน "Hi" → "ข้อความสั้นเกินไป"