class TestStringOperations {

    // Example pg 162 Java Programming Language
    // Returns the number of characters between the
    // first and last occurence of a character within
    // a string
    static int countBetween(String str, char ch) {
        int begPos = str.indexOf(ch);
        if( begPos < 0 )                    // not there
            return -1;
        int endPos = str.lastIndexOf(ch);
        return endPos - begPos - 1;
    }        
    
    // Exercise 8.1
    //  Count the number a times a char appears in a String
    static int count(String str, char ch) {
        int count = 0;
        int begPos = str.indexOf(ch);
        if( begPos < 0 )
            count = begPos;
        else
            count++;
            
        while( begPos >= 0 ) {
            begPos = str.indexOf(ch, begPos + 1);
            if( begPos > 0 )
                count++;
        };     
        return count;
    }
    
    // Exercise 8.2
    //  Count the number of times one string appears in
    //  another string.
    static int countStrs(String str, String subStr) {
        int count = 0;
        int begPos = str.indexOf(subStr);

        if( begPos < 0 )
            count = begPos;
        else
            count++;
            
        while( begPos >= 0 ) {
            begPos = str.indexOf(subStr, begPos + 1);
            if( begPos > 0 )
                count++;
        }    
        return count;
    }
       
    public static void main(String[] args) {
        System.out.println("Count between: \t" +  countBetween("Hello World", 'l') );
        System.out.println("Count l: \t" + count("Hello World", 'l') );
        System.out.println("Count a: \t" + count("Hello World", 'a') );
        System.out.println("Count abc: \t" +  countStrs("abcdefabcdefabc", "abc") );
        System.out.println("Count xyz: \t" + countStrs("abcdefabcdefabc", "xyz") );
    }
}