-3

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?

Cyto
  • 60
  • 1
  • 8
  • And what have you tried so far ? – Konstantin Yovkov May 28 '13 at 21:47
  • 1
    When I take the sentence `"I am walking"` and replace everything except the first and last character to a underscore, I get `"I__________g"`. You need to be way more precise, and post an example that makes sense. Also, you need to show what you have tried, as we're willing to help you, but we are not here to fulfill code requests. – jlordo May 28 '13 at 21:50
  • You are saying *but except the first and last character in a sentence*, but you gave an example `I am w_____g`. This is not the first and the last character in the sentence it's in the word, explain to us please you need in the word or the sentence? – Azad May 28 '13 at 21:52
  • @AzadOmer Thx edited I meant word. – Cyto May 28 '13 at 22:45

2 Answers2

0

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_____? 
arynaq
  • 6,710
  • 9
  • 44
  • 74
0

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.

npr
  • 126
  • 1
  • 10