Rishi
Rishi

Reputation: 45

String Parsing in Java

I am trying to parse a string something like this:

Input "20:00" - output would be "20" Input "02:30" - output would be "2" Input "00:30" - output would be "".

This is how I have written, I don't like the way I am doing it, looking for more efficient way to do this may be in a single scan. Any ideas?

private String getString(final String inputString)
{
    String inputString = "20:00"; // This is just for example       
    final String[] splittedString = inputString.split(":");
    final String firstString = splittedString[0];
    int i;
    for (i = 0; i < firstString.length(); i++)
    {
        if (firstString.charAt(i) != '0')
        {
            break;
        }
    }

    String outputString = "";
    if (i != firstString.length())
    {
        outputString = firstString.substring(i, firstString.length());
    }

    return outputString;
}

Upvotes: 4

Views: 258

Answers (2)

BaroqueBobcat
BaroqueBobcat

Reputation: 10150

You could use java.util.Scanner. Assuming your data is always formatted \d\d:\d\d, you could do something like this.

Scanner s = new Scanner(input).useDelimiter(":");
int n = s.nextInt();
if (n == 0 ) {
  return "";
} else {
  return Integer.toString(n)
}

That way you don't have to scan the string twice--once for the split and once for checking the first split. And, if your data is more complex, you can make your scanner more sophisticated using regexps or something.

Upvotes: 1

Bala R
Bala R

Reputation: 109017

final String firstString = splittedString[0];
int value = Integer.parseInt(firstString);
return value == 0 ? "" : Integer.toString(value);

Upvotes: 2

Related Questions