Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the different methods to parse strings in Java? [closed]

For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of ifs or switches. What are some different ways of parsing strings in Java?

like image 496
agweber Avatar asked Aug 05 '08 23:08

agweber


People also ask

What are parse methods in Java?

The parse() Method of SimpleDateFormat class is used to parse the text from a string to produce the Date. The method parses the text starting at the index given by a start position.

What are parse methods?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert.

What is the use of parse () method in Java explain with an example?

Usually the parse() method receives some string as input, "extracts" the necessary information from it and converts it into an object of the calling class. For example, it received a string and returned the date that was "hiding" in this string.

What is parser parse in Java?

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer. parseInt takes that string value and returns a real number.


2 Answers

I really like regular expressions. As long as the command strings are fairly simple, you can write a few regexes that could take a few pages of code to manually parse.

I would suggest you check out http://www.regular-expressions.info for a good intro to regexes, as well as specific examples for Java.

like image 199
Daniel Broekman Avatar answered Oct 11 '22 21:10

Daniel Broekman


I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this:

  1. Read in the string
    • Split the string into tokens
    • Use a dictionary to convert synonyms to a common form
    • For example, convert "hit", "punch", "strike", and "kick" all to "hit"
    • Perform actions on an unordered, inclusive base
    • Unordered - "punch the monkey in the face" is the same thing as "the face in the monkey punch"
    • Inclusive - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action.
like image 22
andrewrk Avatar answered Oct 11 '22 20:10

andrewrk