ภาพรวม
ตัวอย่างนี้สาธิตการใช้เมธอด indexOf() ของคลาส String เพื่อค้นหาตำแหน่ง (index) ของข้อความย่อยภายในข้อความที่ผู้ใช้ป้อนใน EditText แล้วแสดงผลใน TextView
ขั้นตอนการสร้างโปรเจกต์
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project → Empty Activity → ตั้งชื่อโปรเจกต์ → Finish
ขั้นตอนที่ 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"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="ป้อนชื่อ" />
<Button
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ค้นหา" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp" />
</LinearLayout>
ขั้นตอนที่ 3: เขียน Logic หลัก (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = name.getText().toString().trim();
if (input.isEmpty()) {
name.setError("กรุณาป้อนข้อความ");
return;
}
// ค้นหาตำแหน่งของคำว่า "sai"
int index = input.indexOf("sai");
text.setText("Index ของ 'sai': " + index);
}
});
}
}
การทำงานของ indexOf()
- คืนค่าตำแหน่งเริ่มต้น (0-based index) ของ substring ที่พบครั้งแรก
- คืนค่า
-1หากไม่พบ substring ที่ค้นหา - ค้นหาแบบ Case-sensitive (แยกพิมพ์เล็ก-ใหญ่)
ตัวอย่างผลลัพธ์
| ข้อความที่ป้อน | ผลลัพธ์ | คำอธิบาย |
|---|---|---|
| "Krishna sai" | 8 | พบ "sai" ที่ตำแหน่งที่ 8 |
| "Sai Krishna" | 0 | พบที่ต้นข้อความ |
| "Hello World" | -1 | ไม่พบ "sai" |
ขยายความสามารถ
สามารถปรับเปลี่ยนได้ง่ายเพื่อ:
- ค้นหาข้อความอื่นโดยเปลี่ยนพารามิเตอร์ของ indexOf()
- ใช้
lastIndexOf()เพื่อค้นหาตำแหน่งสุดท้ายที่พบ - ใช้
indexOf(String str, int fromIndex)เพื่อเริ่มค้นหาจากตำแหน่งที่กำหนด