Java - Write code to trim a string with while loop and Character.isWhitespace

Requirements

Write code to trim a string with while loop and Character.isWhitespace

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        CharSequence s = "book2s.com";
        System.out.println(trim(s));
    }/*from w w w  . j av a 2s  . c om*/

    public static CharSequence trim(CharSequence s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        int start = 0;
        int end = s.length() - 1;

        while (start < end && Character.isWhitespace(s.charAt(start))) {
            start++;
        }

        while (end > start && Character.isWhitespace(s.charAt(end - 1))) {
            end--;
        }

        return s.subSequence(start, end);
    }
}

Related Example