এই প্রোগ্রামটি একটি ফাইল থেকে কন্টেন্ট পড়ে, একটি নির্দিষ্ট শব্দ (যেমন "Tutorialspoint") বাদ দিয়ে বাকি সব ক্যারেক্টারকে # দিয়ে রিপ্লেস করে।
অ্যালগরিদম
- ফাইল কন্টেন্ট স্ট্রিং হিসেবে পড়ুন।
split(" ")দিয়ে শব্দে ভাগ করুন (স্পেস ডিলিমিটার)।- প্রতিটি শব্দ চেক করুন: টার্গেট শব্দ হলে অরিজিনাল রাখুন, অন্যথায় সব ক্যারেক্টার
#দিয়ে রিপ্লেস করুন। - রেজাল্ট প্রিন্ট করুন।
উদাহরণ
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ReplaceExcept {
public static String fileToString() throws FileNotFoundException {
String filePath = "D://input.txt";
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
sb.append(sc.nextLine());
}
return sb.toString();
}
public static void main(String args[]) throws FileNotFoundException {
String contents = fileToString();
System.out.println("Contents of the file: \n" + contents);
// স্পেস দিয়ে শব্দে ভাগ
String strArray[] = contents.split(" ");
System.out.println("Words: " + Arrays.toString(strArray));
StringBuffer buffer = new StringBuffer();
String word = "Tutorialspoint"; // সংরক্ষণ করা শব্দ
for(int i = 0; i < strArray.length; i++) {
if(strArray[i].equals(word)) {
buffer.append(strArray[i] + " "); // অরিজিনাল রাখা
} else {
buffer.append(strArray[i].replaceAll(".", "#") + " "); // সব ক্যারেক্টার #
}
}
String result = buffer.toString();
System.out.println("Result:\n" + result);
}
}
আউটপুট
Contents of the file: Hello how are you welcome to Tutorialspoint we provide hundreds of technical tutorials for free. Words: [Hello, how, are, you, welcome, to, Tutorialspoint, we, provide, hundreds, of, technical, tutorials, for, free.] Result: ##### ### ### ### ####### ## Tutorialspoint ## ####### ######### ## ######### ######### ### ####. #################################################
উন্নতির সুযোগ:
split("\\s+")ব্যবহার করলে মাল্টিপল স্পেস/নিউলাইন হ্যান্ডেল হবে।- পাঙ্কচুয়েশন হ্যান্ডলিং (কমা, ফুলস্টপ) আলাদা করতে পারে।
- বড় ফাইলের জন্য স্টREAM প্রসেসিং (BufferedReader + FileWriter) ভালো।