aspose file tools
The moose likes Beginning Java and the fly likes doubt about string replacement Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "doubt about string replacement" Watch "doubt about string replacement" New topic
Author

doubt about string replacement

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
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
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...
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: doubt about string replacement
 
Similar Threads
string manipulation
How we can Count the no.of words in a given String
How to find occurence of substring in a String?
printing
About Adler 32 checksum