Android-এ lastIndexOf() মেথড ব্যবহার করে সাবস্ট্রিংয়ের শেষ অবস্থান বের করা
এই টিউটোরিয়ালে আমরা দেখব কিভাবে Android-এ lastIndexOf() মেথড ব্যবহার করে EditText-এ লিখা স্ট্রিংয়ে নির্দিষ্ট সাবস্ট্রিং (যেমন "sai") এর শেষবার উপস্থিত হওয়ার ইন্ডেক্স বের করা যায়।
প্রয়োজনীয় ধাপসমূহ
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio খুলুন → File → New Project ক্লিক করুন → প্রয়োজনীয় তথ্য পূরণ করে একটি নতুন প্রজেক্ট তৈরি করুন।
ধাপ ২: লেআউট ফাইল সংশোধন করুন (activity_main.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:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="টেক্সট লিখুন"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="শেষ ইন্ডেক্স বের করুন"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
ধাপ ৩: জাভা কোড লিখুন (MainActivity.java)
src/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 {
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 inputText = name.getText().toString().trim();
if (!inputText.isEmpty()) {
// "sai" শব্দটির শেষ ইন্ডেক্স বের করুন
int lastIndex = inputText.lastIndexOf("sai");
text.setText("'sai'-র শেষ ইন্ডেক্স: " + lastIndex);
} else {
name.setError("দয়া করে কিছু লিখুন");
}
}
});
}
}
অ্যাপ্লিকেশন চালানোর পদ্ধতি
- আপনার অ্যান্ড্রয়েড ডিভাইস কম্পিউটারের সাথে সংযুক্ত করুন।
- Android Studio-তে Run আইকনে ক্লিক করুন।
- ডিভাইস সিলেক্ট করুন।
ফলাফল
ইনপুট: "Krishna sai sai"
আউটপুট: "'sai'-র শেষ ইন্ডেক্স: 12"

lastIndexOf() মেথডের ওভারলোড ও ব্যবহার
lastIndexOf(String str)— সাবস্ট্রিংয়ের শেষ অবস্থান।lastIndexOf(String str, int fromIndex)— নির্দিষ্ট ইন্ডেক্স থেকে পিছনে সার্চ।lastIndexOf(int ch)/lastIndexOf(int ch, int fromIndex)— ক্যারেক্টার জন্য।
রিটার্ন ভ্যালু: পাওয়া গেলে ০-ভিত্তিক ইন্ডেক্স, না পেলে -1।
ব্যবহার ক্ষেত্র: ফাইল এক্সটেনশন বের করা (শেষ '.' খুঁজে), লগ পার্সিং, ডুপ্লিকেট চেক ইত্যাদি।