Pls using simple java language We write code that can find and replace in a give
ID: 3907531 • Letter: P
Question
Pls using simple java language
We write code that can find and replace in a given text file. The code you write should take the parameters as command line arguments:
java FindReplace -i <input file> -f "<find-string>" -r "<replace-string>" -o <output file>
< find ? string > ve < replace ? string > it an be any string
Only certain special characters can be found in <find-string>. The question mark (?) Is related to these.
*question mark can be used instead of any character.
"?al" string an be sal ,kal,val
*In addition, a certain set of characters can be given in brackets.
"kng[a,b,f,d,s]ne" string an be kngane,hngbne,kangfne,kangdne,kangsne
So, all you have to do is match all strings that match
<find - string> in the input file <replace -string> and output (output the entire contents of the input file) output file.
The input file needs to remain unchanged.
* Input and output files will be a text file.
Both strings will be separated by a double quotation mark (") character. To change these special characters in Java
you will need to enter an escape character (backslash) like
examples=
java FindReplace -i input.txt -f "sam?jack[3,4,5]" -r "samjack49" -o output.txt
java FindReplace -i doc -f "ali-veli k?rk dokuz elli" -r "ali veli 49 50 " -o doc2
java FindReplace -i input -o output -r "-f" -f "-r"
[replace input -r with -f and write result to output file]
java FindReplaca -o out -i inp -f "[]" -r "{}"
[replace input [] with {} and write result to output file]
java FindReplace -i input.txt -o output.txt -f "[?]" -r "[a]"
[bracketed strings with single characters in it. Replace with [a]]
java FindReplace -i input -o output -f "?" -r "question mark"
java FindReplace -o out -i input -f """ -r " ' "
java FindReplace -i inp -f "sam" -r "jack"
Explanation / Answer
import java.io.*;
import java.util.*;
public class FindReplace{
public static void main(String[] args){
String input = "";
String output = "";
String find = "";
String replace = "";
for (int i = 0; i<args.length; i++){
if (args[i].equals("-o"))
output = args[i+1];
if (args[i].equals("-i"))
input = args[i+1];
if (args[i].equals("-f"))
find = args[i+1];
if (args[i].equals("-r"))
replace = args[i+1];
}
try {
FileInputStream fin = new FileInputStream(input);
FileOutputStream fout = new FileOutputStream(output);
PrintWriter pw = new PrintWriter(fout);
Scanner sc = new Scanner(fin);
while (sc.hasNextLine()){
String line = sc.nextLine();
String str = "" ;
String[] list = line.split(" ");
for (int i = 0; i<list.length; i++){
if (list[i].equals(find)){
str = str + replace + " ";
}
else {
str = str + list[i] + " ";
}
}
pw.println(str);
}
pw.close();
fout.close();
sc.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}