javaarraysstringsplit

Java: Extract values from a String?


I'm new to Java and am trying to extract values from a date-related user input string and split it into a DD-MM-YYYY format.

I tried to use the code below:

String inputString = "s.param1"; 
String[] arraySplit_3 = inputString.split("-");
for (int i=0; i < arraySplit_3.length; i++){
    System.out.println(arraySplit_3[i]);
}

s.param1 gets the input of the user, I use a separate excel file for it.

if s.param1 = 15-05-2010

I wish to get this output:

DD: 15

MM: 05

YYYY: 2010

Is there a way to create a method like this?


Solution

  • If your s.param1 is variable which gets date in String, so you shouldn't use it in quotes. Otherwise it will be String. And variable name could not be with dot. It could be sParam1.
    But when you set date instead of s.param1 your created method should work.

    // input "15-05-2010"
    String inputString = sparam1; 
    String[] arraySplit_3 = inputString.split("-");
    for (int i=0; i < arraySplit_3.length; i++){
        System.out.println(arraySplit_3[i]);
    }
    

    The output will be:
    15
    05
    2010

    If you want to add some chars before the numbers don't use for loop. Use it like this:

    // ...
    if (arraySplit_3 > 2) {
        System.out.println("DD: " + arraySplit_3[0]);
        System.out.println("MM: " + arraySplit_3[1]);
        System.out.println("YYYY: " + arraySplit_3[2]);
    }
    

    Then output will be:
    DD: 15
    MM: 05
    YYYY: 2010