开发者

String Parsing in Java

开发者 https://www.devze.com 2023-03-12 16:23 出处:网络
I am trying to parse a string something like this: Input \"20:00\" - output would be \"20\" Input \"02:30\" - output would be \"2\"

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.leng开发者_高级运维th());
    }

    return outputString;
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消