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
}
}
>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(?!$)
-
(?<!^)xis a Negative Lookbehind and ensure that there is no start of string before thex:xis not first char -
x(?!$)is a Negative Lookahead and ensure that there is no end of string after thex:xis not a last char
public static String stringX(String s) {
return s.replaceAll("(?<!^)x(?!$)", "");
}