File
StringReader example
With this example we are going to demonstrate how to use a StringReader. The StringReader is a character stream whose source is a string. In short, to use a StringReader you should:
- Create a new StringReader with a specified String.
- Create a new StreamTokenizer using the reader.
- Iterate over the tokens of the tokenizer, and for every token if it is a word increase the value of a counter. In this way we can count the words of the String using the tokenizer.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.io.StreamTokenizer; import java.io.StringReader; public class Main { public static void main(String[] args) throws Exception { StringReader strReader = new StringReader("Java Code Geeks is awsome!"); int wc = 0; StreamTokenizer tokenizer = new StreamTokenizer(strReader); while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if (tokenizer.ttype == StreamTokenizer.TT_WORD) { wc++; } } System.out.println("Word count in this string: " + wc); } }
Output:
Word count in this string: 5
This was an example of how to use a StringReader in Java.