Skip to content

how do you remove a letter from a string when using substring

So I am trying to remove all the x’s from this string! Of course I can use replaceAll but I want it to remove one by one each x and then print it! But it keeps either erroring out or I just can’t seem to remove it! Of course I know how to find the x but idk how to remove afterwards!

public class Test1
    public static void main(String[] args)
        String message = "Ix lovex youxxx";
        for(int x = 0 ; message.length() > 0 ; x++){
            String v = message.substring(x, x+1);
            if (v.indexOf("x") > -1){
                String w = message.substring(v, v+1);



You could work with StringBuilder, which has an inbuilt method deleteCharAt.

public static void main(String[] args) {
    String msg = "Ix lovex youxxx";
    char toExtract = 'x';
    StringBuilder sb;

    while (msg.indexOf(toExtract) != -1) {
        sb = new StringBuilder(msg);
        int index = msg.indexOf(toExtract);
        msg = sb.toString();


Ix lovex youxxx
I lovex youxxx
I love youxxx
I love youxx
I love youx
I love you


As long as the string msg still has the character to extract, a StringBuilder is made containing the current message, the first index is removed and then saved back to msg and printed.