Java Reference
In-Depth Information
ceded) by one or more spaces as a single delimiter, but you will have to wait until Chapter 15 to find out
how it's done.
The second block of output has 12 tokens. This is because there is an extra empty token at the end of the
list of tokens that is eliminated when the second argument to the split() method is 0. The extra token
is there because the end of the string is always a delimiter, so the period followed by the end of the string
identifies an empty token.
Modified Versions of String Objects
You can use a couple of methods to create a new String object that is a modified version of an existing
String object. These methods don't change the original string, of course — as I said, String objects are
immutable.
To replace one specific character with another throughout a string, you can use the replace() method.
For example, to replace each space in the string text with a slash, you can write:
String newText = text.replace(' ', '/'); // Modify the string text
The first argument of the replace() method specifies the character to be replaced, and the second argu-
ment specifies the character that is to be substituted in its place. I have stored the result in a new variable
newText here, but you can save it back in the original String variable, text , if you want to effectively re-
place the original string with the new modified version.
To remove whitespace from the beginning and end of a string (but not the interior) you can use the
trim() method. You can apply this to a string as follows:
String sample = " This is a string ";
String result = sample.trim();
After these statements execute, the String variable result contains the string "This is a string" .
This can be useful when you are segmenting a string into substrings and the substrings may contain leading
or trailing blanks. For example, this might arise if you were analyzing an input string that contained values
separated by one or more spaces.
Creating Character Arrays from String Objects
You can create an array of variables of type char from a String object by using the toCharArray() method
that is defined in the String class. Because this method creates an array of type char[] and returns a ref-
erence to it, you only need to declare the array variable of type char[] to hold the array reference — you
don't need to allocate the array. For example:
String text = "To be or not to be";
char[] textArray = text.toCharArray(); // Create the array from the string
The toCharArray() method returns an array containing the characters of the String variable text , one
per element, so textArray[0] contain 'T' , textArray[1] contains 'o' , textArray[2] contain ' ' , and
so on.
Search WWH ::




Custom Search