Title: JH3 String Methods Help
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

JH3 String Methods Help

For the methods:

- countOccurrences(char c)
- countUpperCaseLetters()
- countLowerCaseLetters()

You should find the following useful for any string:


String someString = "Four score and seven years ago our For-Fathers ...";

for (int i =0; i < someString.length( ); i++)
{
    char c2 = someString.charAt(i);
    // do whatever you want with the character
}

//Depending on what you are looking for, you will have appropriate if statements:

if (c2 >= 'A' && c2 <= 'Z')  // testing for upper case

if (c2 >= 'a' && c2 <= 'z') //  testing for lower case

if (c2 == c ) // testing for a specific character

Note that in the MyStringMethods class, we are interested in the string that shows up as an instance variable:

String myStr;

Note the myStr takes on a value in one of 2 ways.

1. a call is made to readString( ) and the value is entered at the keyboard.
2. a call is made to setString(String s)

The countOccurrences(String s) is a little trickier:

Suppose that:

String myStr = "Go to the sea to see the sea creatures down by the sea shore";

Suppose that we want to know how many occurrences of "sea" are in this string.

You will want to know about the String methods:

indexOf("sea") // returns an integer index of the first occurrence of "sea". -1 is returned if nothing is found

indexOf("sea", startingIndex); - Similar to above except that we start at startingIndex instead of zero.

Your code will look something like:


String toFind="sea";
int index = myStr.indexOf(toFind);  // find first occurrence
while(index >= 0)
{
   //Increment our counter;
   //Move to the next instance of "toFind" with a call:
   index = myStr.indexOf(toFind, someInteger);
}


Last Modified: January 7, 2015 1:16 AM