I have a Java string that contains spaces on the right and left. I want to remove the empty space on both sides.
The code 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); } }
The result I got ...
Amebiasis length 13 Amebiasis length 11 Amebiasis length 13 ltrim Amebiasis rtrim Amebiasis
Somehow it does not remove the empty space. What is wrong with my code, please help me with this.
source share