Trim a String with given character from Left or Right in Android or Java

Sometime you need to trim or remove a charecter from left or right. For example:

http://devstudioonline.com

You need to remove http:// from left. Then you need a function to trim from left side with given charecters or string.

public static String ltrim(String str, String trimchar){
     if(trimchar.length()<=str.length()){
          if(str.substring(0,trimchar.length()).equalsIgnoreCase(trimchar)){
              str = str.substring(trimchar.length(),str.length());
          }
     }
     return str;
}

Now you can trim http:// using this function:

String sample = "http://devstudioonline.com";
Strimg domain = ltrim(sample, "http://");

In the same way we can also rtrim a string.

public static String rtrim(String str, String trimchar){
     if(str.substring(str.length()-trimchar.length(),str.length()).equalsIgnoreCase(trimchar)){
          str = str.substring(0,str.length() - trimchar.length());
     }
     return str;
}

 

Keywords: