in Advanced 

Resource preview: Know-how

HomeResource preview:
Log in

Trim any character from a string using java

Exercise is to trim a char in java.
Lets suppose we want to trim custom character from a java string.
The standard functionality from java suggest trimming only spaces via :
    public static void main(String[] args) {
        String s = "\t hello ";
        System.out.println("s=\"" + s.trim()+"\"");
    }

Which gives the result s="hello"

Now we want to remove a character from left and right side of a string. We call this operation "trim".

Here is my solution, not very understandable, but as quick as possible.
    public static String trim(StringBuilder s, char toTrim) {
        int originalLen = s.length();
        int len = s.length();
        int st = 0;

        while ((st < len) && (s.charAt(st) == toTrim)) {
            st++;
        }
        while ((st < len) && (s.charAt(len - 1) == toTrim)) {
            len--;
        }
        return ((st > 0) || (len < originalLen)) ? s.substring(st, len) : s.toString();
    }


Now lets test with underscore:
    public static void main(String[] args) {
        String s = "___hello_";
        System.out.println("s=\"" + trim(new StringBuilder(s), '_')+"\"");
    }


which gives the result:
s="hello"

I hope this will be useful for you.
Vote:
Comments: 0
Please vote! Your opinion matters!
If you want to share knowledge with the others, post a resource
Add resource
| Home | Hall of fame | Registration | Log in | Terms of service | Privacy policy | Help | Contacts | RSS |