Search code examples
javaandroidreplaceall

Java replaceall except first and last character in every word


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?


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_____?