C:\> java TokenTester Enter a string: val = 12+8 val = 12 + 8
Notice that the spaces are returned as well as the other delimiters and tokens. This might not be quite what you want. You might like to ignore spaces completely and use only "=+-" as delimiters. The following does that:
import java.io.*; import java.util.*; public class TokenTester { public static void main ( String[] args ) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a string:"); String data = stdin.readLine(); StringTokenizer tok = new StringTokenizer( data, "=+-", true ); // NO space before = while ( tok.hasMoreTokens() ) System.out.println( tok.nextToken().trim() ); } }
Now nextToken()
returns the Strings
"val ", "=", " 12", "+", and "8".
The trim()
method trims spaces off both ends
of these Strings.