Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to make left and right trim on Java String

Tags:

java

I have Java String which contain white space on both right and left side. I want to remove white space from both side.

Code that I tried...

public class Test {

    public static void main(String args[])
    {
        String abc = "  Amebiasis  ";
        System.out.println(abc +" length "+abc.length());
        System.out.println(rtrim(abc)+" length "+rtrim(abc).length());
        System.out.println(ltrim(abc)+" length "+ltrim(abc).length());

        String ltrim = abc.replaceAll("^\\s+","");
        String rtrim = abc.replaceAll("\\s+$","");

        System.out.println("ltrim"+ltrim);
        System.out.println("rtrim"+rtrim);
    }

    public static String rtrim(String s) {
        int i = s.length()-1;
        while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
            i--;
        }
        return s.substring(0,i+1);
    }

    public static String ltrim(String s) {
        int i = 0;
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
            System.out.println("s.charAt(i)  "+s.charAt(i));
            i++;
        }
        return s.substring(i);
    }
}

Output that I got...  

  Amebiasis   length 13
  Amebiasis length 11
  Amebiasis   length 13
ltrim  Amebiasis  
rtrim  Amebiasis

Somehow it doesn't remove white space. What is wrong with my code, please help me on that.

like image 824
Vijay Avatar asked Oct 02 '13 05:10

Vijay


1 Answers

Defaultly available trim()

String abc = "  Amebiasis  ";
System.out.println(""+abc.trim());
like image 195
newuser Avatar answered Sep 24 '22 14:09

newuser