ภาพรวม
ตัวอย่างนี้สาธิตการใช้เมธอด equalsIgnoreCase() เพื่อเปรียบเทียบสตริงสองค่า โดยไม่สนใจตัวพิมพ์เล็ก-ใหญ่ (Case-insensitive comparison)
ขั้นตอนการสร้างโปรเจกต์
ขั้นตอนที่ 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"
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: โค้ดหลัก (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;
}
// เปรียบเทียบแบบไม่สนใจ Case
boolean isMatch = input.equalsIgnoreCase("point");
text.setText("ตรงกับ 'point' (ไม่สนใจ Case): " + isMatch);
}
});
}
}
ความแตกต่างระหว่าง equals() และ equalsIgnoreCase()
| เมธอด | Case-sensitive | ตัวอย่าง |
|---|---|---|
equals() | ใช่ | "Point".equals("point") → false |
equalsIgnoreCase() | ไม่ | "Point".equalsIgnoreCase("point") → true |
ตัวอย่างผลลัพธ์
| ข้อความที่ป้อน | equalsIgnoreCase("point") | equals("point") |
|---|---|---|
| "point" | true | true |
| "POINT" | true | false |
| "Point" | true | false |
| "PoInT" | true | false |
| "tutorialspoint" | false | false |
กรณีการใช้งานจริง
- การยืนยันรหัสผ่าน/รหัส PIN ที่ไม่ควรสนใจ Case
- การค้นหาข้อมูลที่ผู้ใช้อาจพิมพ์ผสมผสานตัวพิมพ์เล็ก-ใหญ่
- การตรวจสอบคำสั่งเสียง (Voice commands)
- การกรองข้อมูลจาก API ที่อาจมีรูปแบบไม่คงที่
หมายเหตุประสิทธิภาพ
equalsIgnoreCase() มีประสิทธิภาพน้อยกว่า equals() เล็กน้อย เนื่องจากต้องแปลง Case ก่อนเปรียบเทียบ แต่ความแตกต่างนั้นน้อยมาก สำหรับการใช้งานทั่วไปไม่ควรเป็นปัญหา