एंड्रॉइड में EditText इनपुट का पहला कैरेक्टर अक्षर है या नहीं जांचना
यह ट्यूटोरियल दिखाता है कि उपयोगकर्ता इनपुट का पहला कैरेक्टर अल्फाबेट (A-Z, a-z) है या नहीं कैसे पहचानें।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट (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:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:hint="कुछ टाइप करें"
android:layout_height="wrap_content" />
<Button
android:id="@+id/buttonPanel"
android:text="जांचें"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
चरण 3: MainActivity कोड (java/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editQuery = findViewById(R.id.edit_query);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String data = editQuery.getText().toString().trim();
if (!data.isEmpty()) {
char firstChar = data.charAt(0);
// Character.isLetter() यूनिकोड अक्षर जांचता है (हिंदी, अंग्रेजी, आदि)
if (Character.isLetter(firstChar)) {
Toast.makeText(MainActivity.this,
"'" + firstChar + "' एक अक्षर (Alphabet) है",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,
"'" + firstChar + "' अक्षर नहीं है",
Toast.LENGTH_LONG).show();
}
} else {
editQuery.setError("कृपया टेक्स्ट दर्ज करें");
}
}
});
}
}
मुख्य बिंदु
- Character.isLetter() - सभी यूनिकोड अक्षर पहचानता है (लैटिन, देवनागरी, साइरिलिक, आदि)
- केवल अंग्रेजी (A-Z, a-z) के लिए:
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') Character.isAlphabetic() अधिक व्यापक है (अक्षर + अक्षर जैसे चिह्न)
वैकल्पिक दृष्टिकोण
// केवल अंग्रेजी अक्षर के लिए
boolean isEnglishLetter = (firstChar >= 'a' && firstChar <= 'z') ||
(firstChar >= 'A' && firstChar <= 'Z');
// Regex उपयोग करके
boolean isLetter = String.valueOf(firstChar).matches("[a-zA-Z]");
// Kotlin एक्सटेंशन
fun Char.isEnglishLetter() = this in 'a'..'z' || this in 'A'..'Z'
ऐप चलाएं
कोई भी टेक्स्ट दर्ज करें - पहला कैरेक्टर अक्षर है या नहीं बताएगा (संख्या, स्पेस, विशेष चिह्न के लिए "नहीं")।