Android में स्ट्रिंग का पहला नॉन-रिपीटिंग कैरेक्टर ढूंढना
यह उदाहरण दर्शाता है कि Android में दी गई स्ट्रिंग में पहला नॉन-रिपीटिंग (अनोखा) कैरेक्टर कैसे ढूंढा जाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project पर जाएं और आवश्यक विवरण भरकर एक नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट XML में कोड जोड़ें
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">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
उपरोक्त कोड में, हमने पहला नॉन-रिपीटिंग कैरेक्टर दिखाने के लिए TextView लिया है।
चरण 3: MainActivity.java में कोड जोड़ें
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.util.LinkedHashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
TextView textView;
String inputString = "tutorialspoint";
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// LinkedHashMap - इंसर्शन ऑर्डर बनाए रखता है
LinkedHashMap<Character, Integer> charCountMap = new LinkedHashMap<>();
// 1. प्रत्येक कैरेक्टर की फ्रीक्वेंसी गिनें
for (char c : inputString.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// 2. पहला कैरेक्टर ढूंढें जिसकी फ्रीक्वेंसी 1 हो
Character firstNonRepeating = null;
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() == 1) {
firstNonRepeating = entry.getKey();
break;
}
}
TextView textView = findViewById(R.id.text);
if (firstNonRepeating != null) {
textView.setText("पहला नॉन-रिपीटिंग: '" + firstNonRepeating + "'");
} else {
textView.setText("कोई नॉन-रिपीटिंग कैरेक्टर नहीं मिला");
}
}
}
एप्लिकेशन चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें। Android Studio में प्रोजेक्ट की एक्टिविटी फाइल खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और परिणाम देखें।


परिणाम: स्ट्रिंग "tutorialspoint" के लिए:
- t: 2, u: 1, o: 2, r: 1, i: 2, a: 1, l: 1, s: 1, p: 1, n: 1
- पहला नॉन-रिपीटिंग: 'u' (इंडेक्स 1)
क्यों LinkedHashMap?
| Map प्रकार | ऑर्डर | उपयुक्त |
|---|---|---|
| HashMap | कोई गारंटी नहीं | नहीं |
| TreeMap | सॉर्टेड (कैरेक्टर ऑर्डर) | नहीं |
| LinkedHashMap | इंसर्शन ऑर्डर | ✓ हाँ |