Java string analysis

I am trying to parse a line something like this:

Entrance "20:00" - the output will be "20" Input "02:30" - the output will be "2" Input "00:30" - the output will be "".

This is how I wrote, I don’t like the way I do it, looking for a more efficient way to do this can be in one 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; } 
+4
source share
2 answers
 final String firstString = splittedString[0]; int value = Integer.parseInt(firstString); return value == 0 ? "" : Integer.toString(value); 
+2
source

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

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

Thus, you do not need to scan the line twice - once for splitting and once for checking the first split. And, if your data is more complex, you can make your scanner more complex using regular expressions or something else.

+1
source

All Articles