简体   繁体   中英

Java: Split a string into separate string and integer variables

I have been looking for an answer but I haven't had luck finding one that can quite help me (someone may know where to point me).

I want to split a string up into a string variable and two integer variables. I am wondering if there is anyway to user the string split method I discovered and use it for int variables through some other way?

Code:

import java.util.Scanner;

public class StringInputStream {
   public static void main (String [] args) {
      Scanner inSS = null;
      String userInput = "Jan 12 1992";
      inSS = new Scanner(userInput);

      String userMonth = "";
      int userDate = 0;
      int userYear = 0;

      // Can modify anything below here
      String[] temp = userInput.split(" ", 2); // "1" means stop splitting after one space
      userMonth = temp[0];
      userDate = temp[1];
      userYear = temp[2];
      // Can modify anything above here

      System.out.println("Month: " + userMonth);
      System.out.println("Date: " + userDate);
      System.out.println("Year: " + userYear);

      return;
   }
}

Example output:

Month: Jan
Date: 12
Year: 1992

Based on your comments, and code using a Scanner . I think you wanted

userMonth = inSS.next();
userDate = inSS.nextInt();
userYear = inSS.nextInt();

But if the Scanner isn't required for your assignment, then you could certainly eliminate it and use something like

String userInput = "Jan 12 1992";
String[] tokens = userInput.split("\\s+"); // <-- split on one or more spaces
String userMonth = tokens[0];
int userDate = Integer.parseInt(tokens[1]);
int userYear = Integer.parseInt(tokens[2]);

I do not want to use a sledge-hammer to crack a nut :-) but depending on the flexibility that you need in you application with respect to the input provided, you could use a parser for your problem. If you take the grammar below and put it into ANTLR , you could parse the input string and extract the semantic elements from it. You could even handle different input permutations such as Jan 1999 12 , 1999 Mar 12 , and so on.

grammar SimpleMixed;
fragment A:('a'|'A');
fragment B:('b'|'B');
fragment C:('c'|'C');
fragment D:('d'|'D');
fragment E:('e'|'E');
fragment F:('f'|'F');
fragment G:('g'|'G');
fragment H:('h'|'H');
fragment I:('i'|'I');
fragment J:('j'|'J');
fragment K:('k'|'K');
fragment L:('l'|'L');
fragment M:('m'|'M');
fragment N:('n'|'N');
fragment O:('o'|'O');
fragment P:('p'|'P');
fragment Q:('q'|'Q');
fragment R:('r'|'R');
fragment S:('s'|'S');
fragment T:('t'|'T');
fragment U:('u'|'U');
fragment V:('v'|'V');
fragment W:('w'|'W');
fragment X:('x'|'X');
fragment Y:('y'|'Y');
fragment Z:('z'|'Z');

s: userinput EOF;
userinput: month date year
    | month year date
    | year month date
    | year date month
    | date year month
    | date month year;

month: Month;
date: Date;
year: Year;
Month: J A N |  F E B | M A R | A P R | M A Y | J U N | J U L | A U G | S E P      |
O C T | N O V | D E C;

Date: [1-9][0-2]?;

Year: [1-9][0-9][0-9][0-9];


WS  :  [ \t\r\n]+ -> skip;

Let's suppose a user provides input jan 1999 12 . After parsing it with the parser generated from Antlr from the grammar above, you would get the parse tree below from which you could easily extract the semantic elements based on which you can infer the datatype and create the appropriate objects (eg int for year and date, and String for month).

在此输入图像描述

Seems like you're dealing with date strings, better use the specific library.

Java 8

import java.time.format.DateTimeFormatter;
import java.time.temporal.*;

TemporalAccessor d = DateTimeFormatter.ofPattern("MMM DD yyyy").parse("Jan 12 1992")
d.get(ChronoField.YEAR); // 1992
d.get(ChronoField.MONTH_OF_YEAR); // 1
d.get(ChronoField.DAY_OF_MONTH); // 12

Before Java 8 (java.text.SimpleDateFormat)

Date d = new SimpleDateFormat("MMM DD yyyy").parse("Jan 12 1992");
Calendar c = Calendar.getInstance();
c.setTime(d);
c.get(Calendar.YEAR); // 1992
c.get(Calendar.MONTH); // 0 - yeah, it starts from 0, embarrassingly
c.get(Calendar.DAY_OF_MONTH); // 12

Or use JodaTime

DateTimeFormat.forPattern("MMM DD yyyy").parseDateTime("Jan 12 1992");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM