26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

550 Strings and Characters Chapter 10<br />

42 output += "\n\"hello\" is located at index " +<br />

43 letters.indexOf( "hello" );<br />

44<br />

45 // test lastIndexOf <strong>to</strong> find a substring in a string<br />

46 output += "\n\nLast \"def\" is located at index " +<br />

47 letters.lastIndexOf( "def" );<br />

48<br />

49 output += "\nLast \"def\" is located at index " +<br />

50 letters.lastIndexOf( "def", 25 );<br />

51<br />

52 output += "\nLast \"hello\" is located at index " +<br />

53 letters.lastIndexOf( "hello" );<br />

54<br />

55 JOptionPane.showMessageDialog( null, output,<br />

56 "Demonstrating String Class \"index\" Methods",<br />

57 JOptionPane.INFORMATION_MESSAGE );<br />

58<br />

59 System.exit( 0 );<br />

60 }<br />

61<br />

62 } // end class StringIndexMethods<br />

Fig. Fig. 10.6 10.6 The String class searching methods (part 2 of 2).<br />

The statements at lines 16–23 use method indexOf <strong>to</strong> locate the first occurrence of<br />

a character in a String. If indexOf finds the character, indexOf returns the index of<br />

that character in the String; otherwise, indexOf returns –1. There are two versions of<br />

indexOf that search for characters in a String. The expression on line 17 uses method<br />

indexOf that takes one integer argument, which is the integer representation of a character.<br />

Remember that a character constant in single quotes is of type char and specifies<br />

the integer representation of the character in the Unicode character set. The expression at<br />

line 20 uses the second version of method indexOf, which takes two integer arguments—<br />

the integer representation of a character and the starting index at which the search of the<br />

String should begin.<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!