|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You can get the character at a particular index within a string, string buffer, or string builder by invoking thecharAtaccessor method. The index of the first character is 0; the index of the last islength()-1. For example, the following code gets the character at index 9 in a string:Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9);Use the charAtmethod to get a character at a particular index.The figure also shows that to compute the index of the last character of a string, you have to subtract 1 from the value returned by the
lengthmethod.If you want to get more than one character from a string, string buffer, or string builder, you can use the
substringmethod. Thesubstringmethod has two versions, as shown in the following table:
The substringMethods in theString,StringBufferandStringBuilderClassesMethod Description String substring(int)
String substring(int, int)Returns a new string that is a substring of this string, string buffer, or string builder.The first integer argument specifies the index of the first character. The second integer argument is the index of the last character -1. The length of the substring is therefore the secondintminus the firstint. If the second integer is not present, the substring extends to the end of the original string.The following code gets from the Niagara palindrome the substring that extends from index 11 to index 15, which is the word "roar":
Use theString anotherPalindrome = "Niagara. O roar again!"; String roar = anotherPalindrome.substring(11, 15);substringmethod to get part of a string, string buffer, or string builder. Remember that indices begin at 0.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.