Search code examples
javastringstring-parsing

Parsing a string for information in java


I would like to know if there is a way to parse this string to get the numerical values associated with each descriptor. I would like to use these values to update totals and averages and such.

The string looks like this:

D/TESTING:﹕ 17-08-2015 13:28:41 -0400
    Bill Amount: 56.23      Tip Amount: 11.25
    Total Amount: 67.48     Bill Split: 1
    Tip Percent: 20.00

The code for the string looks like this:

String currentTransReport = getTime() +
            "\nBill Amount: " + twoSpaces.format(getBillAmount()) +
            "\t\tTip Amount: " + twoSpaces.format(getTipAmount()) +
            "\nTotal Amount: " + twoSpaces.format(getBillTotal()) +
            "\t\tBill Split: " + getNumOfSplitss() +
            "\nTip Percent: " + twoSpaces.format(getTipPercentage() * 100);

I want to extract each of the values, like the bill amount, and then store the value in a variable to be used. I have access to the ONLY string with the information, not the code or information that builds the string.


Solution

  • Try something like this to get started? This will take all characters starting after the substring you are currently looking for, and ending at the tab character after the substring. You may need to change this tab character to something else. Hopefully syntax is OK, I've been away from java for awhile.

    String myString = "17-08-2015 13:28:41 -0400Bill Amount: 56.23      Tip Amount: 11.25  Total Amount: 67.48     Bill Split: 1 Tip Percent: 20.00 ";
    String substrings[] = {"Bill Amount: ", "Tip Amount: ", "Total Amount: ", "Bill Split: ", "Tip Percent: "};
    String results[] = new String[5];
    
    for (int i = 0; i < substrings.length; i++){
        int index = myString.indexOf(substrings[i]) + substrings[i].length(); // where to start looking
        String result = myString.substring(index, myString.indexOf(" ", index));
        results[i] = result;
    }
    

    Just confirmed, this mostly works, only problem is there is no " " character on the end of the string.