How can I replace more line in one line?

I want to insert "OB" before every vowel. I've tried the code below:

String out=txt.toUpperCase();

out=out.replaceAll("A","OBA");
out=out.replaceAll("E","OBE");
out=out.replaceAll("I","OBI");
out=out.replaceAll("O","OBO");
out=out.replaceAll("U","OBU");
out=out.replaceAll("Y","OBY");

      

When I use this code above, it replaces A

with OBA

, but then when it comes to replacing O

with OBO

, it replaces O

with the original text as well as O

in OBA

. For example, for "I WON'T"

I want an output "OBI WOBON'T"

, but it gives instead "OBOBI WOBON'T"

, since the O

from OBI

from the first line is treated as a vowel.

I need a solution that does not replace the new one O

with encryption.

+3


source to share


5 answers


Since it replaceAll

accepts a regular expression, you can use references to the captured elements in your replacement string:

out=out.replaceAll("[AEIOUY]", "OB$0");

      



  • [AEIOUY]

    grabs one character from the list AEIOUY

  • $0

    in the replacement string, denotes the character that was captured.

Here is a demon .

+7


source


You can reference the mapped group using $1

, so replacing it with AB$1

:



out.replaceAll("([AEIOUY])", "OB$1")

      

+3


source


move "O", "OBO" to the beginning to prevent duplication

String out=txt.toUpperCase();

out=out.replaceAll("O","OBO");
out=out.replaceAll("A","OBA");
out=out.replaceAll("E","OBE");
out=out.replaceAll("I","OBI");
out=out.replaceAll("U","OBU");
out=out.replaceAll("Y","OBY");

      

+1


source


If you don't want to use regular expressions:

HashMap<Character, String> replace = new HashMap<Character, String>() {{
            put('A',"OBA");
            put('E',"OBE");
            put('I',"OBI");
            put('O',"OBO");
            put('U',"OBU");
            put('Y',"OBY");
}};

final StringBuilder res = new StringBuilder();
String test = "I WON'T";

test
 .chars()
 .mapToObj(c -> (char) c)
 .forEach(c -> res.append(replace.getOrDefault(c, Character.toString(c))));
System.out.println(res);

      

+1


source


Something like this can also be done, replace OB with '- @' (any 2 characters that we can be sure they won't appear in the string) and replace them with OB at the end:

public static void main (String [] args) {String text = "I WILL NOT",

text = text.replaceAll("A", "-@A");
text = text.replaceAll("E", "-@E");
text = text.replaceAll("I", "-@I");
text = text.replaceAll("O", "-@O");
text = text.replaceAll("U", "-@U");
text = text.replaceAll("Y", "-@Y");
System.out.println(text);       
text = text.replaceAll("-@", "OB");     
System.out.println(text);
}

      

Output

- @I W- @ ON'T OBI WOBON'T

-1


source







All Articles