Java - Write code to Remove trailing whitespace from the given string.

Requirements

Write code to Remove trailing whitespace from the given string.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*from w  w  w. j a  va 2s  . c  o m*/
 
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(trimTrailing(str));
    }

    /**
     * Removes trailing whitespace from the given string.
     *
     * @param str the string to trim.
     *
     * @return a copy of the string with trailing whitespace removed, or the original
     *         string if no trailing whitespace could be removed.
     */
    public static String trimTrailing(String str) {
        int index = str.length();

        while ((index > 0) && Character.isWhitespace(str.charAt(index - 1))) {
            index--;
        }

        if (index != str.length()) {
            return str.substring(0, index);
        }
        return str;
    }
}