Vijay Vijay - 4 years ago 246
Java Question

Want to make left and right trim on Java String

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+$","");


public static String rtrim(String s) {
int i = s.length()-1;
while (i >= 0 && Character.isWhitespace(s.charAt(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));
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.

Answer Source

Defaultly available trim()

String abc = "  Amebiasis  ";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download