1

I have a file with a big list of strings which is of the form

key1=value1  
key2=value2  
...

I need to add a string for eg. (Long) after every equal sign. And create a new file with these new strings:

key1=(Long)value1.
key2=(Long)value2.
...  

How to implement this with a java program?

3
  • 1
    Search for = and replace it by =(Long). Look in the methods of class String for usefule methods that you can use for this. Commented Feb 26, 2013 at 9:05
  • 2
    Or you could do this in one line with awk. awk -F= '{ print $1"=(Long)"$2 }' bigfile Commented Feb 26, 2013 at 9:07
  • Might I suggest using the Apache StringUtils replace over the default java replace if you can? Commented Feb 26, 2013 at 9:20

3 Answers 3

5
BufferedReader b = new BufferedReader(new FileInputStrem(file));

while(b.readLine() != null) {
     System.out.println(line.replace("=", "=(Long)"));
}

b.close();
Sign up to request clarification or add additional context in comments.

Comments

2
"key1=value1".replace("=", "=(Long)");

respectively:

"key1=value1".replace("=", "=" + String.valueOf(123l));

This will only work in Java >1.4 and if no = could be in the key or value

Comments

0
public class StringReplace
{
    public static void main(String[]args)
    {
        String str1 = "key1=value";
        String rep = "=(Long)";

        //Printing Current String
        System.out.println(str1);

        //Replacing the String
        str1 = str1.replaceAll("=", rep);

        //Printing new value
        System.out.println(str1);
    }
}

Use replaceAll() or replace() to replace all the matches found.

The above is the easiest way. You can go with loops checking for matches as well. But it will take lot of memory, if you are checking for lot of matches, it will be a panic.

3 Comments

You don't really need a replaceAll here. Simply using str1.replace would suffice.
@RohitJain: I believe it is using an algorithm which uses less memory
The only difference between them is, replaceAll takes regex as parameter, whereas, replace does simple string replacement. You can also look into their source code for implementations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.