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.
Defaultly available trim()
String abc = " Amebiasis ";
System.out.println(""+abc.trim());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With