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.
source to share
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 listAEIOUY
-
$0
in the replacement string, denotes the character that was captured.
Here is a demon .
source to share
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);
source to share
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
source to share