String Extraction

There might be occasions in your programs when you want to extract portions of a string. The String class provides this functionality with a set of methods for just that purpose. You can determine the character at a given position in the string, for example, by calling the charAt method, like this:

String str = "This is a string";
char chr = str.charAt(6);

In these lines, the character variable chr ends up with a value of s, which is the fifth character in the string. Why didn't chr become equal to i? Remember that in Java, you start counting array elements at zero rather than one.

A similar method, getChars(), enables you to copy a portion of a String object to a character array:

 String str = "This is a string"; char chr[] ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.