I want to scan an input line character by character and produce Strings based on valid tokens which are “true”, “false”, “^” “&”, “!”, “(”, “)”
For example if i was given a string such as String line = true & ! (false ^ true)
I would have to produce the tokens "true", "&", "!", "(", "false", "^", "true", ")"
I have been trying to use split() to divide the string into tokens and store them in an array like this String[] result = line.split(" ")
, and then just using a bunch of if-statements inside a loop to see if the token at that index matches any of the valid tokens and just returning the token. this is kind of what i have been trying to use so far
for(int i = 0; i < line.length();i++){
if(result[i].equals("true") || result[i].equals("false") || result[i].equals("^")
|| result[i].equals("&") || result[i].equals("!") || result[i].equals("(")
|| result[i].equals(")")){
nextToken = result[i];
}
but obviously this wont extract valid tokens that are adjacent to one another, such as when the string contains something like this (true
or this true^false
, which should return three tokens being "true", "^", "false"
. Is there a way to divide a string that doesn't contain spaces or any special characters into tokens i am interested in?