Manchukonda Manoj
Manchukonda Manoj

Reputation: 17

How to remove middle character in a string in java?

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());
    }

}

Upvotes: 0

Views: 9695

Answers (2)

AnjuT
AnjuT

Reputation: 176

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());
}

Upvotes: 0

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));

Upvotes: 2

Related Questions