Java - Write code to Return the index within the given string of the x. occurrence of the specified character.

Requirements

Write code to Return the index within the given string of the x. occurrence of the specified character.

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   ww w. j ava  2 s .c  o m
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        char character = 'a';
        String str = "book2s.com";
        int x = 42;
        System.out.println(indexOf(character, str, x));
    }

    /**
     * Returns the index within the given string of the <em>x.</em> occurrence of the
     * specified character.
     *
     * @param character character to search.
     * @param str the string to search.
     * @param x <em>x.</em> occurrence of the character to search for.
     *
     * @return s the index within the given string of the <em>x.</em> occurrence of the
     *         given character. Returns <code>-1</code> if the specified character is
     *         not contained in the given string or it occurs less than the specified
     *         occurrence to look for.
     */
    public static int indexOf(char character, String str, int x) {
        for (int i = 1, pos = -1; (pos = str.indexOf(character, pos + 1)) > -1; i++) {
            if (i == x) {
                return pos;
            }
        }

        return -1;
    }
}