user3120023
user3120023

Reputation: 307

How to get one character from a String

I am creating a game in java and want the user to enter a String for direction to move, in the form:

MOVE <DIRECTION>

Where direction is either N, E, S or W. I want to be able to just get the individual character between the "<" and the ">", what would be the best way to go about doing this, as currently i cannot think of a decent method, given that this String may be of varying size e.g. it could be:

"MOVE<S>

Due to there not being a space between MOVE and <.

Thanks very much for any help:)

Upvotes: 0

Views: 156

Answers (3)

aliteralmind
aliteralmind

Reputation: 20163

How about this?

import  java.util.regex.Matcher;
import  java.util.regex.Pattern;

/**
   <P>{@code java GetDirectionXmpl}</P>
 **/
public class GetDirectionXmpl  {
  //Create a matcher with a dummy-string, so it can be reused (reset).
  private static Matcher mMove = Pattern.compile("^MOVE *<([NEWS])>$").matcher("");

   public static final void main(String[] igno_red)  {
     System.out.println("Null if badly formatted");

     System.out.println(getDirection("MOVE<S>"));
     System.out.println(getDirection("MOVE<BAD>"));
     System.out.println(getDirection("MOVE<W>"));
     System.out.println(getDirection("MOVE <N>"));
     System.out.println(getDirection("MOVE<N>BAD"));
   }
   public static final String getDirection(String s_input)  {
     //Reuse the same matcher
     mMove.reset(s_input);

     if(!mMove.matches())  {
        return  null;
     }
     return  mMove.group(1);
  }
}

Output:

[C:\java_code\]java GetDirectionXmpl
Null if badly formatted
S
null
W
N
null

Upvotes: 0

Tim B
Tim B

Reputation: 41188

You can use regular expressions to extra data from a String:

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

and more specifically

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html

Upvotes: 0

Zavior
Zavior

Reputation: 6452

String s = "MOVE<S>";
char c = s.charAt(s.indexOf("<") + 1);

Use indexOf to find the index of "<", and then get the character after if using charAt+1. But really, you should look up the string api. It is very useful to know.

Upvotes: 5

Related Questions