How to remove middle character in a string in java?

9.3k Views Asked by At

I am trying to print the string without its middle character, but I am not getting the required output.

public class StringIndexEliminator {
    public static void main(String[] args) {
        String str = "CARS";
        int l = str.length();
        int s = (l+1)/2;
        System.out.println(l);
        StringBuffer sb = new StringBuffer(str);
        System.out.println(sb.deleteCharAt(s).toString());
    }

}
2

There are 2 best solutions below

3
On

No need to use a stringBufffer (there is no race conditions) use the StringBuilder and then remove the char at length/2

StringBuilder sb = new StringBuilder(str);
System.out.println(sb.deleteCharAt(str.length() / 2));
1
On

You have to check the length of the string in even or odd, and after that print the string you want.

Hope this will do what you wanted.

String str = "CARS";
int l = str.length();

if((l % 2) == 0){
    System.out.println(str);
}else{
    StringBuffer sb = new StringBuffer(str);
    System.out.println(sb.deleteCharAt((l-1)/2).toString());
}