Java - Write code to Return the offset of the first non-whitespace character of the given string.

Requirements

Write code to Return the offset of the first non-whitespace character of 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.
 *///  w w  w. j a  va  2 s  .co m
 
//package com.book2s;

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

    /**
     * Returns the offset of the first non-whitespace character of the given string.
     *
     * @param str a string.
     *
     * @return the offset of the first non-whitespace character in the given string.
     *         Returns <code>-1</code> if no non-whitespace character could be found.
     */
    public static int indexOfNonWhitespace(String str) {
        return indexOfNonWhitespace(str, 0);
    }

    /**
     * Returns the offset of the first non-whitespace character of the given string.
     *
     * @param str a string.
     * @param beginOffset DOCUMENT ME!
     *
     * @return the offset of the first non-whitespace character in the given string.
     *         Returns <code>-1</code> if no non-whitespace character could be found.
     *
     * @throws IllegalArgumentException DOCUMENT ME!
     */
    public static int indexOfNonWhitespace(String str, int beginOffset) {
        if (beginOffset < 0) {
            throw new IllegalArgumentException("beginOffset < 0 -- "
                    + beginOffset);
        }

        for (int i = beginOffset, size = str.length(); i < size; i++) {
            switch (str.charAt(i)) {
            case ' ':
            case '\t':
                break;

            default:
                return i;
            }
        }

        return -1;
    }
}