Sirmittens
Sirmittens

Reputation: 29

Removing a letter from a string at a specific position

I am trying to locate the * in a string and remove it and the characters in front and before it. for example the string st*tilly will output silly

this is what I have so far

public static String starOut(String str) {
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.charAt(i) == '*') {
            StringBuilder sb = new StringBuilder(str);
            sb.deleteCharAt(i);
            sb.deleteCharAt(i+1);
            sb.deleteCharAt(i-1);
            sb.toString();
        }
    }
    return sb;
}

Upvotes: 1

Views: 48

Answers (1)

WJS
WJS

Reputation: 40062

You could do it like this. It uses a regular expression

  • . matches any character.
  • \\* matches an asterisk. It has to be escaped because by itself it has a special meaning in regular expressions.
String str = "The sx*yilly dog was acting very st*tilly";
str = str.replaceAll(".\\*.","");
System.out.println(str);

Prints

The silly dog was acting very silly

Upvotes: 1

Related Questions