Question

What I want to accomplish is to replace a sentence to underscore, but except the first and last character in a word.

Example:

I am walking

To:

I am w_____g

Is this possible with regex?

Was it helpful?

Solution

This answer should work, in future be a bit more detailed in your questions and do tell us what you have tried, people are more willing to help then ;)

public static void main(String[] args) {
    System.out.println(replaceAll("Hello", '_'));

    String sentence = "Hello Mom What Is For Dinner?";
    StringBuilder sentenceReformed = new StringBuilder();

    for (String word : sentence.split(" ")) {
        sentenceReformed.append(replaceAll(word, '_'));
        sentenceReformed.append(" ");
    }

    System.out.println(sentenceReformed);
}

public static String replaceAll(String word, char replacer) {
    StringBuilder ret = new StringBuilder();
    if (word.length()>2) {
        ret.append(word.charAt(0));
        for (int i = 1; i < word.length() - 1; i++) {
            ret.append(replacer);
        }
        ret.append(word.charAt(word.length() - 1));
        return ret.toString();
    }

    return word;
}

Out:

H__o
H___o M_m W__t Is F_r D_____? 

OTHER TIPS

I think you could do this with regular expressions, by looking at where the matches start and end. However, it seems like in this case regular expressions are overkill. It is simpler to allocate a new character array, copy the first and last character of the input to that array, and the fill in the middle with underscores, then allocate a string from that character array, like so:

public class ReplaceMiddle {

public static String replaceMiddle (String s) {
  char[] c = new char[s.length()];

  c[0] = s.charAt(0);

  for (int i = 1; i < s.length() - 1; i++) {
    c[i] = '_';
  }

  c[s.length() - 1] = s.charAt(s.length() - 1);

  return new String(c);

}

public static void main(String[] argv) {
   System.out.println( ReplaceMiddle.replaceMiddle("I want a pumpkin."));
}

}

Output:

I_______________.

Note that this does not handle zero length strings, or the case of s being null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top