public class StringIndexMethods
1: // Fig. 29.5: StringIndexMethods.java
2: // String searching methods indexOf and lastIndexOf.
3:
4: public class StringIndexMethods
5: {
6: public static void main( String args[] )
7: {
8: String letters = "abcdefghijklmabcdefghijklm";
9:
10: // test indexOf to locate a character in a string
11: System.out.printf(
12: "'c' is located at index %d\n", letters.indexOf( 'c' ) );
13: System.out.printf(
14: "'a' is located at index %d\n", letters.indexOf( 'a', 1 ) );
15: System.out.printf(
16: "'$' is located at index %d\n\n", letters.indexOf( '$' ) );
17:
18: // test lastIndexOf to find a character in a string
19: System.out.printf( "Last 'c' is located at index %d\n",
20: letters.lastIndexOf( 'c' ) );
21: System.out.printf( "Last 'a' is located at index %d\n",
22: letters.lastIndexOf( 'a', 25 ) );
23: System.out.printf( "Last '$' is located at index %d\n\n",
24: letters.lastIndexOf( '$' ) );
25:
26: // test indexOf to locate a substring in a string
27: System.out.printf( "\"def\" is located at index %d\n",
28: letters.indexOf( "def" ) );
29: System.out.printf( "\"def\" is located at index %d\n",
30: letters.indexOf( "def", 7 ) );
31: System.out.printf( "\"hello\" is located at index %d\n\n",
32: letters.indexOf( "hello" ) );
33:
34: // test lastIndexOf to find a substring in a string
35: System.out.printf( "Last \"def\" is located at index %d\n",
36: letters.lastIndexOf( "def" ) );
37: System.out.printf( "Last \"def\" is located at index %d\n",
38: letters.lastIndexOf( "def", 25 ) );
39: System.out.printf( "Last \"hello\" is located at index %d\n",
40: letters.lastIndexOf( "hello" ) );
41: } // end main
42: } // end class StringIndexMethods
43:
44: /**************************************************************************
45: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
46: * Pearson Education, Inc. All Rights Reserved. *
47: * *
48: * DISCLAIMER: The authors and publisher of this book have used their *
49: * best efforts in preparing the book. These efforts include the *
50: * development, research, and testing of the theories and programs *
51: * to determine their effectiveness. The authors and publisher make *
52: * no warranty of any kind, expressed or implied, with regard to these *
53: * programs or to the documentation contained in these books. The authors *
54: * and publisher shall not be liable in any event for incidental or *
55: * consequential damages in connection with, or arising out of, the *
56: * furnishing, performance, or use of these programs. *
57: *************************************************************************/