// (from the Carter book)
// Example 4 --> how to use "charAt" vs. "indexOf" in Strings.
//
// Both method versions, called "printLocations" (below), print the
// indices in the String "s" of the location that contains the
// character "c". The first of these methods uses the String method
// "charAt" to examine every character in the String "s". The second
// of these methods uses "indexOf" to jump to the locations in which
// the character "c" occurs. In the second method, the constant
// called "NOT_FOUND" is set to -1, which is the value returned by
// the "indexOf" method if it fails to find the specified character.
//
// Here are the definitions of the 2 versions of "printLocations":
public class StringMethodsExample4
{
public static void main (String[] args)
{
String s = "Vancouver 2010 Winter Olympics";
printLocations ('0', s);
} // main method
// public static void printLocations (char c, String s)
// {
// System.out.println ("printLocations method # 1 (using 'charAt'): ");
// System.out.println();
// for (int i = 0; i < s.length(); i++)
// {
// if (s.charAt(i) == c)
// {
// System.out.println ("'c' = " + c);
// System.out.println ("'i' = " + i);
// }
// }
// } // printLocations method # 1
public static void printLocations (char c, String s)
{
System.out.println ("printlocations method # 2 (using 'indexOf'): ");
System.out.println ();
final int NOT_FOUND = -1;
int next = s.indexOf (c);
while (next != NOT_FOUND)
{
System.out.println ("'c' = " + c);
System.out.println ("'next' = " + next);
next = s.indexOf (c, next + 1);
}
} // printLocations method # 2
} // StringMethodsExample4 class
No comments:
Post a Comment