Reading Characters from String Builders – Selected API Classes

Reading Characters from String Builders

The following methods can be used for reading characters in a string builder:

Click here to view code image

char charAt(int index)             
From the
 CharSequence
interface (p. 444)
.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Copies characters from the current string builder into the destination character array. Characters from the current string builder are read from index srcBegin to index srcEnd-1, inclusive. They are copied into the destination array (dst), starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1. The number of characters copied is (srcEnd-srcBegin). An IndexOutOfBoundsException is thrown if the indices do not meet the criteria for the operation.

Click here to view code image

IntStream chars()                   
From the
 CharSequence
interface (p. 444).
int length()                       
From the
 CharSequence
interface (p. 444).

The following is an example of reading the contents of a string builder:

Click here to view code image

StringBuilder strBuilder = new StringBuilder(“Java”);      // “Java”, capacity 20
char charFirst = strBuilder.charAt(0);                     // ‘J’
char charLast  = strBuilder.charAt(strBuilder.length()-1); // ‘a’

Searching for Substrings in String Builders

The methods for searching substrings in string builders are analogous to the ones in the String class (p. 451).

Click here to view code image

int indexOf(String substr)
int indexOf(String substr, int fromIndex)

int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)

Examples of searching for substrings in a StringBuilder:

Click here to view code image

StringBuilder banner2 = new StringBuilder(“One man, One vote”);
//                                         01234567890123456
int subInd1a = banner2.indexOf(“One”);         // 0
int subInd1b = banner2.indexOf(“One”, 3);      // 9
int subInd2a = banner2.lastIndexOf(“One”);     // 9
int subInd2b = banner2.lastIndexOf(“One”, 10); // 9
int subInd2c = banner2.lastIndexOf(“One”, 8);  // 0
int subInd2d = banner2.lastIndexOf(“One”, 2);  // 0

Extracting Substrings from String Builders

The StringBuilder class provides the following methods to extract substrings, which are also provided by the String class (p. 453).

Click here to view code image

String substring(int startIndex)
String substring(int startIndex, int endIndex)

CharSequence subSequence(int start, int end)
From the
 CharSequence
interface
(
p. 444
).

Examples of extracting substrings:

Click here to view code image

StringBuilder bookName = new StringBuilder(“Java Gems by Anonymous”);
//                                          01234567890123456789012
String title  = bookName.substring(0,9);   // “Java Gems”
String author = bookName.substring(13);    // “Anonymous”

Leave a Reply

Your email address will not be published. Required fields are marked *