Monday, 12 December 2011

string manipulation in java example - Getting Characters and Substrings by Index


You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1. For example, the following code gets the character at index 9 in a string:
String anotherPalindrome = 
"Niagara. O roar again!";
char aChar = anotherPalindrome.charAt(9);
Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:
Use the charAt method to get a character at a particular index.
If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions, as shown in the following table:
The substring Methods in the String Class
MethodDescription
String substring(int beginIndex, int endIndex)Returns a new string that is a substring of this string. The first integer argument specifies the index of the first character. The second integer argument is the index of the last character - 1.
String substring(int beginIndex)Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string.
The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word "roar":
String anotherPalindrome = 
"Niagara. O roar again!";
String roar =
anotherPalindrome.substring(11, 15);
Use the substring method to get part of a string.