9

I'm writing a program that will replace multiple words in a single string. I'm using this code but it is replacing word but giving result in two different lines. I want multiple words replaced and output in one single line.

import java.util.*;
public class ReplaceString {
    public static void main(String[] args) {
        new ReplaceString().run();
    }

    public void run()
    {

        System.out.println("Input String:\n");////
        Scanner keyboardScanner = new Scanner(System.in);/////
        String inString = keyboardScanner.nextLine();/////
        String strOutput = inString.replace("call me","cm");
        System.out.println(strOutput);

        String strOutput1 = inString.replace("as soon as possible","asap");
        System.out.println(strOutput1);      

    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
shumaila
  • 129
  • 2
  • 2
  • 4

9 Answers9

24

If you want to do it in a single statement you can use:

String strOutput = inString.replace("call me","cm").replace("as soon as possible","asap");

Alternatively, if you have many such replacements, it might be wiser to store them in some kind of data structure such as a 2d-array. For example:

//array to hold replacements
String[][] replacements = {{"call me", "cm"}, 
                           {"as soon as possible", "asap"}};

//loop over the array and replace
String strOutput = inString;
for(String[] replacement: replacements) {
    strOutput = strOutput.replace(replacement[0], replacement[1]);
}

System.out.println(strOutput);
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 7
    It's not proper way doing it because if you have input `"abc"` and `replacements = {{"a"}{"b"},{"b"}{"c"}}` you should expect `"bcc"` on output but you will get `"ccc"`. The solution was described here - [stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most](http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most). – patryk.beza Jan 20 '13 at 11:05
7

Of course it prints two lines: you have two print statements. Use this code:

import java.util.*;

public class ReplaceString {
    public static void main(String[] args) {
        new ReplaceString().run();
    }

    public void run()
    {

        System.out.println("Input String:\n");////
        Scanner keyboardScanner = new Scanner(System.in);/////
        String inString = keyboardScanner.nextLine();/////
        String shortMessage = shortifyMessage(inString);
        System.out.println(shortMessage);
    }

    public String shortifyMessage(String str)
    {
        String s = str;
        s = s.replace("call me", "cm");
        s = s.replace("as soon as possible", "asap");
        // Add here some other replacements

        return s;
    }
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
4

All above answers could be correct. However, replacing each string once is not efficient. Following code from Apache Commons StringUtils will help it to efficiently replace all the strings in one go.

    System.out.println("Input String:\n");////
    Scanner keyboardScanner = new Scanner(System.in);/////
    String inString = keyboardScanner.nextLine();/////
StringUtils.replaceEach(inString, new String[]{"call me", "as soon as possible"}, new String[]{"cm", "asap"});

Please note that: above method doesn't work on replacing the words in previous substitution result. For example:

StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})

will give result : "dcte"

Ameer Tamboli
  • 1,218
  • 12
  • 20
4

Now you can use StringUtils in commons-lang3 package.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.7</version>
</dependency>

Code like below:

strOutput = StringUtils.replaceEach(inString, new String[]{"call me", "as soon as possible"}, new String[]{"cm", "asap"});
jayxhj
  • 2,829
  • 1
  • 19
  • 24
1

Instead of using replace use replaceAll which worked for me

String strOutput = inString.replaceAll("call me","cm").replaceAll("as soon as possible","asap");
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
0

Use MessageFormat.format(queryString, retrieveArguments().toArray());

hardik pansuria
  • 208
  • 1
  • 3
  • 13
0

The root problem is that, once you've made the first replacement, you can not work again with the same initially given string. I think the correct way of doing it would be using different copies and moving from one to the other the content while it is being replaced May be, better than this, the solution could be just do an extra replacement after each done replacement to erase the already replaced patterns. ;)

pepito apellido
  • 81
  • 1
  • 2
  • 6
0

Use System.out.print() instead of System.out.println()

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0
    String strOutput1 = inString.replace("as soon as possible","asap");

You should change that to

    String strOutput1 = strOutput .replace("as soon as possible","asap");
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588