Home > Blockchain >  How to replace substrings of string with different substrings in JAVA?
How to replace substrings of string with different substrings in JAVA?

Time:12-21

I have to replace different substrings of a single string with different strings. For e.g.

 String str =" She was born on DATE at TIME on DAY";

I want to replace DATE, TIME and DAY parts of string with different string values. Using replace(), I am able to replace just one part of the string. But I am working looking for is a solution to replace all these substrings with different strings at one go.

CodePudding user response:

The best you could perhaps do would be to use an iterative regex approach:

String str = "She was born on DATE at TIME on DAY";
Map<String, String> repl = new HashMap<>();
repl.put("DATE", "DATE_REPL");
repl.put("TIME", "TIME_REPL");
repl.put("DAY", "DAY_REPL");

Pattern pattern = Pattern.compile("\\b(DATE|TIME|DAY)\\b");
Matcher m = pattern.matcher(str);
StringBuffer buffer = new StringBuffer();
  
while(m.find()) {
    m.appendReplacement(buffer, repl.get(m.group(1)));
  }
m.appendTail(buffer);

System.out.println("input:  "   str);
System.out.println("output: "   buffer.toString());

This prints:

input:  She was born on DATE at TIME on DAY
output: She was born on DATE_REPL at TIME_REPL on DAY_REPL

Here we are searching on the regex alternation \b(DATE|TIME|DAY)\b. Each time we find a match in the string, we do a lookup in a hashmap for the replacement string.

CodePudding user response:

The easiest way to do so would be to make date, time, and day separate variables, so that

String str = "She was born on "   date   " at "   time   " on "   day;

CodePudding user response:

The built-in String replace doesn't support replacing multiple occurrences. So, you will need to write your own method to do so.

The code below assumes oldstuff contains unique strings. If they are not unique, you would have to write a different solution.

   public static void main(String[] args) {
        String original = " She was born on DATE at TIME on DAY";
        String[] oldstuff = {"DATE", "TIME", "DAY"};
        String[] newstuff = {"Feb 14, 2000", "midnight", "Tuesday"};

        System.out.println(original);
        String updated = replace(original, oldstuff, newstuff);
        System.out.println(updated);

    }

    static String replace(String str, String[] oldstuff, String[] newstuff) {
        for (int i = 0; i < oldstuff.length; i  ) {
            str = str.replace(oldstuff[i], newstuff[i]);
        }
        return str;
    }

Output:

 She was born on DATE at TIME on DAY
 She was born on Feb 14, 2000 at midnight on Tuesday

A better solution would be to scan word by word, replacing only a match is found.

    static String replace2(String str, String[] oldstuff, String[] newstuff){
        StringBuilder sb = new StringBuilder();
        java.util.Scanner s = new Scanner(str);
        int index = 0;
        while(s.hasNext()){
            String word = s.next();
            if (word.equals(oldstuff[index])){
                sb.append(" ").append(newstuff[index]).append(" ");
                index  ;
            } else {
                sb.append(" ").append(word).append(" ");
            }
        }
        
        return sb.toString();
    }

CodePudding user response:

Try this.

public static void main(String[] args) {
    String str =" She was born on DATE at TIME on DAY";

    List<String> list = List.of("(date)", "(time)", "(day)");
    Iterator<String> iterator = list.iterator();
    String output = Pattern.compile("DATE|TIME|DAY").matcher(str)
        .replaceAll(m -> iterator.next());

    System.out.println(output);
}

output:

 She was born on (date) at (time) on (day)

CodePudding user response:

In one go

String str =" She was born on DATE at TIME on DAY";
str = str.replaceAll("DATE", "2021-12-21").replaceAll("TIME", "11:20").replaceAll("DAY", "Tue");
  • Related