rishav rishav - 4 months ago 34
Java Question

how to parse integer from a long string

I want to parse two values from a string in android studio.
I cannot change the data type from web so I need to parse an Intt.The string that I receive from web is

How can I get these values i.e. 5 and 10 from the string "5am-10am".
Thanks in advance for help.


So, the code below shows step by step how to parse the format you are given. I also added in the steps to use the newly parsed Strings as ints so you can perform arithmetic on them. Hope this helps.

        `/*Get the input*/
        String input = "5am-10am"; //Get the input

        /*Separate the first number from the second number*/
        String[] values = input.split("-"); //Returns 'values[5am, 10am]'

        /*Not the best code -- but clearly shows what to do*/
        values[0] = values[0].replaceAll("am", ""); 
        values[0] = values[0].replaceAll("pm", "");
        values[1] = values[1].replaceAll("am", "");
        values[1] = values[1].replaceAll("pm", "");

        /*Allows you to now use the string as an integer*/
        int value1 = Integer.parseInt(values[0]);
        int value2 = Integer.parseInt(values[1]);

        /*To show it works*/
        int answer = value1 + value2;
        System.out.println(answer); //Outputs: '15'`