কোন ফাংশন অন্য স্ট্রিংয়ের সাথে একটি স্ট্রিং প্রতিস্থাপন করতে পারে?
উদাহরণ # 1: কি প্রতিস্থাপন করবে "HelloBrother"সঙ্গে "Brother"?
উদাহরণ # 2: কি প্রতিস্থাপন করবে "JAVAISBEST"সঙ্গে "BEST"?
উত্তর:
এটি ব্যবহার করে দেখুন: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence ,% 20java.lang.CharSequence%29
String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");
System.out.println(r);
এটি "ভাই আপনি কেমন আছেন!" মুদ্রণ করবে
অতিরিক্ত ভেরিয়েবল ব্যবহার না করার সম্ভাবনা রয়েছে
String s = "HelloSuresh";
s = s.replace("Hello","");
System.out.println(s);
একটি স্ট্রিংকে অন্যটির সাথে প্রতিস্থাপন করা নীচের পদ্ধতিগুলিতে করা যেতে পারে
পদ্ধতি 1: স্ট্রিং ব্যবহার করেreplaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
পদ্ধতি 2 : ব্যবহারPattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
পদ্ধতি 3 : Apache Commonsনীচের লিঙ্কে সংজ্ঞায়িত হিসাবে ব্যবহার করা:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
আরেকটি পরামর্শ, আসুন আমরা স্ট্রিংয়ে দুটি একই শব্দ আছে বলে নিই
String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.
প্রতিস্থাপন ফাংশনটি পরিবর্তন করবে প্রতিটি পংক্তিটি প্রথম প্যারামিটারে দ্বিতীয় প্যারামিটারে দেওয়া হয়
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
এবং আপনি একই ফলাফলের জন্য প্রতিস্থাপনও সমস্ত পদ্ধতি ব্যবহার করতে পারেন
System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister
আপনি যদি আগে অবস্থিত ঠিক প্রথম স্ট্রিং পরিবর্তন করতে চান,
System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.