Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using replaceAll on a string doesn't work

I tried to solve this task, but I failed because return won’t work.
I’m new to java and hope you can help me.

The task is to delete every x in a string, but not the first and last one.

public class Main {
    
     public static String stringX(String s) { 
         boolean start = s.startsWith("x");
         boolean end = s.endsWith("x");
         int end1 = s.length() - 1;
         if (start & end) { 
                s.substring(1, end1).replace("x", "");
                
            } else {
                s.replaceAll("x", "");
            }
        return s;
    }

    public static void main(String[] args) {
        String result = stringX("xxHix");
        System.out.println(result); // => xHix

        System.out.println(stringX("abxxxcd")); // => abcd
        System.out.println(stringX("xabxxxcdx")); // => xabcdx
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The operation you’re using doesn’t modify s inplace, you need to retrieve the updated string

s = s.substring(1, end1).replace("x", "");
s = s.replaceAll("x", "");

But the substring + replace won’t work as it removes the first and last char too


You’d better replace all x, then add where it’s needed

public static String stringX(String s) { 
     String trimmed = s.replace("x", "");
     if(s.startsWith("x"))
         trimmed = "x" + trimmed;
     if(s.endsWith("x"))
         trimmed += "x";
    return trimmed;
}

Or use a nice regex (?<!^)x(?!$)

  • (?<!^)x is a Negative Lookbehind and ensure that there is no start of string before the x : x is not first char

  • x(?!$) is a Negative Lookahead and ensure that there is no end of string after the x : x is not a last char

public static String stringX(String s) { 
    return s.replaceAll("(?<!^)x(?!$)", "");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading