Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Question

  1. Aug 13, 2009 #1
    Hi guys,

    I was wondering if anyone could explain to me/point me in the right direction on how to manipulate a String read in from the user in a particular way. I'm trying to read in a String, and then I want to sort of split the string up into ints and chars and associate them to variables.
    For instance:
    If I have a string: 6G2N42B, is there a way to access the ints '6', '2', '42' and a way to access the chars 'G', 'N' and 'B' ?

  2. jcsd
  3. Aug 13, 2009 #2


    User Avatar
    Gold Member

    You can use the Scanner class:
    For example, the output of
  4. Aug 13, 2009 #3


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    This will work without having to put empty spaces in your input string:

    String inputString = "6G2N42B";
    String expression = "(\\d*+)"; // Searches for all groups of numbers
    Pattern myPattern = Pattern.compile(expression);
    Matcher matcher = myPattern.matcher(inputString);
    System.out.println("matcher.group(): " + matcher.group());

    expression = "(\\D*+)"; // Searches for all groups of non-numbers
    myPattern = Pattern.compile(expression);
    matcher = myPattern.matcher(inputString);

    while (matcher.find()) {
    System.out.println("matcher.group(): " + matcher.group());


    matcher.group(): 6
    matcher.group(): 2
    matcher.group(): 42
    matcher.group(): G
    matcher.group(): N
    matcher.group(): B
  5. Aug 13, 2009 #4
    Thanks, I'll give that a try :)
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Java Question
  1. Java Question (Replies: 2)

  2. Java question (Replies: 5)

  3. Java Question (Replies: 2)

  4. Question about Java (Replies: 4)