Java Reference
In-Depth Information
for (int i = 0 ; i< subStr.length ; i++)
subStr[i] = st.nextToken();
The
StringTokenizer
object also has a method
hasMoreTokens()
that returns
true
if the string
contains more tokens and
false
when there are none left. We could therefore also extract all the
tokens from our string like this:
int i = 0;
while(st.hasMoreTokens() && i<subStr.length)
subStr[i++] = st.nextToken();
The loop will continue to extract tokens from the string as long as there are still tokens left, and as long
as we have not filled the array,
subStr
. Of course, we should never fill the array since we created it to
accommodate all the tokens but it does no harm here to verify that we don't. It is also a reminder of
how you can use the
&&
operator.
Try It Out - Using a Tokenizer
Based on what we have just discussed, the whole program to do what the previous example did is as follows:
import java.util.StringTokenizer; // Import the tokenizer class
public class TokenizeAString {
public static void main(String[] args) {
String text = "To be or not to be"; // String to be segmented
StringTokenizer st = new StringTokenizer(text); // Create a tokenizer for it
String[] subStr = new String[st.countTokens()]; // Array to hold the tokens
// Extract the tokens
for (int i = 0 ; i< subStr.length ; i++) {
subStr[i] = st.nextToken();
}
// Display the substrings
for(int i = 0; i < subStr.length; i++) {
System.out.println(subStr[i]);
}
}
}
The
import
statement is necessary because the
StringTokenizer
class is not in the
java.lang
package whose classes are imported by default, but in the
java.util
package. The program should
produce output that is identical to that of the previous example. It's a lot simpler though; isn't it?
Modified Versions of String Objects
There are a couple of methods that you can use to create a new
String
object that is a modified
version of an existing
String
object. They don't change the original string, of course - as we 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 our string
text
with a slash,
you could write: