简体   繁体   中英

Replacing first, middle and last letter in a word on Java

I have a big text with hundreds of O,o. Example:

String s = "Hello world, One!";

How can I replace letter O , o if it is first, last and middle letter in the word?

s.replace("o", "1");

I want: Hell1, w2rld, 3ne in all my text. Also I want to have possibility to select any other letter.

The idear is how to select first, middle and last letter in a word?

There's a few ways I can think of doing it, each one would require a loop, as the value you are replacing with changes, something like...

String s = "Hello world, two!";
int count = 1;
while (s.contains("o")) {
    s = s.replaceFirst("o", Integer.toString(count));
    count++;
}
System.out.println(s);

or

String s = "Hello world, two!";
StringBuilder sb = new StringBuilder(s);
int count = 1;
int index = -1;
while ((index = sb.indexOf("o")) != -1) {
    sb.replace(index, index + 1, Integer.toString(count));
    count++;
}
s = sb.toString();
System.out.println(s);

or you could use String#split and re-stitch the String back together, but it's a little more complicated

for example

If I understand you correctly you an use regex engine or to be more precise methods from Matcher class:

  • appendReplace(StringBuffer sb, replacement) - which adds to buffer sb text which exists until match is founded but instead of match will add value described in replacement parameter
  • appendTail(StringBuffer) - adds to buffer rest of text after last match.

Demo:

String s = "Hello world, two!";

Pattern p = Pattern.compile("o",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
int counter = 0;

while(m.find()){
    m.appendReplacement(sb, Integer.toString(++counter));
}
m.appendTail(sb);

String result = sb.toString();
System.out.println(result);

Output: Hell1 w2rld, tw3!

String s = "Hello world, two!";
String before = s;
int i = 1;
while (!(s = before.replaceFirst("o|O", Integer.toString(i++))).equals(before)) {
    before = s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM