Java - Write code to Strip any white space of the end of a string.

Requirements

Write code to Strip any white space of the end of a string.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s = "   book2s.com   ";
        System.out.println(strip(s));
    }//from  w w w.ja va  2  s  .  c  o m

    /**
     * Strips any white space of the end of a string.
     */
    public static String strip(String s) {
        StringBuffer sb = new StringBuffer();
        int spaces = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                if (spaces > 0)
                    return (sb.toString());
                else
                    spaces++;
            } else {
                sb.append(s.charAt(i));
                spaces = 0;
            }
        }
        return (sb.toString());
    }
}