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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button