Hi friends! i got a problem with strings. i want to read a line from a file and replace a part of the line with new string.i want to compare whether the old string exists in the line or not and if exists i have to replace with the new string.i can not predict that there can be spaces in the line. can any body help in solving the problem. thanks kiran
Apu Nahasapeemapetilon
Ranch Hand
Joined: Sep 06, 2000
Posts: 51
posted
0
Pretty easy, I think. What do we do when we don't find string to be replaced? line = line read from file oldstr = string to be replace newstr = string to replace oldstr result = line with oldstr replaced with newstr //first does old string exist int pos; pos = line.indexOf (oldstr); if (pos > 0) //we found it { result = line.substring (0, pos) + newstr + line.substring ( pos + oldstr.length()) ; } else //we didn't find it { //now what??? result = line; } return result;
Serge Plourde
Ranch Hand
Joined: Jun 23, 2000
Posts: 140
posted
0
Hi, bkkumar! This may be more than want you needed. But I found it chalenging to do, so maybe just keep what you need. I called it SNR (Search and Replace). <code> import java.io.*; import java.util.*; public class SNR { public static void main(String[] args) throws IOException { System.out.println("Your file: " + args[0]); System.out.println("...will have its string(s): " + args[1]); System.out.println("...replaced with : " + args[2]); BufferedReader in = new BufferedReader( new FileReader(args[0]) ); String newText = new String(); String line; StringTokenizer st; String token;
while ( (line = in.readLine()) != null ) { st = new StringTokenizer(line, " ,.-?!", true); while (st.hasMoreTokens()) { token = st.nextToken(); newText += (token.equals(args[1]) ? args[2] : token); } newText+="\n"; } in.close(); BufferedReader inNewText = new BufferedReader( new StringReader(newText) ); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( args[0] ) ) ); while ( (line = inNewText.readLine()) != null) out.println(line); out.close(); } } </code> Of course you'll have to catch possible exceptions and make sure that the arguments are in proper number, etc...