Preethi Jain Preethi Jain - 7 months ago 12
Java Question

How to Split the String by symbol name and Date in this case

I have got a String in this format

FUTSTKACC28-APR-2016

ACC is a symbol and 28-APR-2016 is a expiry date
FUTSTK is predefined word

How to retrieve values symbol and Date in this case

For example how to get
ACC

and

28-APR-2016

some sample data

FUTSTKACC26-MAY-2016
FUTSTKACC28-APR-2016
FUTSTKACC30-JUN-2016
FUTSTKADANIENT26-MAY-2016
FUTSTKADANIENT28-APR-2016
FUTSTKADANIENT30-JUN-2016

Answer

You have a fixed length prefix word and a fixed length date. You can remove the prefix, and then take the substrings from the right by the 11 characters in your dates. Something like,

String[] sample = { "FUTSTKACC26-MAY-2016", "FUTSTKACC28-APR-2016", 
        "FUTSTKACC30-JUN-2016", "FUTSTKADANIENT26-MAY-2016", 
        "FUTSTKADANIENT28-APR-2016", "FUTSTKADANIENT30-JUN-2016" };
String predefWord = "FUTSTK";
for (String input : sample) {
    if (input.startsWith(predefWord)) {
        input = input.substring(predefWord.length());
        // There are 11 characters in the date format
        String symbol = input.substring(0, input.length() - 11);
        String dateStr = input.substring(input.length() - 11);
        System.out.printf("symbol=%s, date=%s%n", symbol, dateStr);
    }
}

Output is

symbol=ACC, date=26-MAY-2016
symbol=ACC, date=28-APR-2016
symbol=ACC, date=30-JUN-2016
symbol=ADANIENT, date=26-MAY-2016
symbol=ADANIENT, date=28-APR-2016
symbol=ADANIENT, date=30-JUN-2016