开发者

Convert a String into an Integer starting with 0

I have to convert from Strings the first 2 characters into an int. The problem is when a string st开发者_如何学JAVAarts with 09 that it get converted in 1 and the year looks like 2001 and not 2009.

this is what I have, maybe there are better methods ...

String s = longString.substring(0, 2); // 09asdasdas
int jahr = Integer.parseInt(s);


...and the year looks like 2001 and not 2009...

Not entirely sure I get your question, but it may depend on how you print it. The following code prints a leading 0 if necessary:

String longString = "09asdasdas";
String s = longString.substring(0, 2); 
int jahr = Integer.parseInt(s);
System.out.printf("Year 20%02d.", jahr);  // prints "2009"

Compare with this snippet

String longString = "59asdasdas";         // <-- Changed to "59....."
String s = longString.substring(0, 2); 
int jahr = Integer.parseInt(s);
System.out.printf("Year 20%02d.", jahr);  // prints "2059"

(Here is an ideone demo.)


There's no need to get rid of the leading 0, but if you want to, here's one way to do it...

Here's how to get rid of the leading 0 if any and it will work fine for any number from "00" to "99" (which your question and substring(0,2) seems to imply):

Integer.parseInt(s.substring(0, 2).replaceAll("^[0]", ""));


You're using a leading zero for decimal manipulation. Bad practise, because it can be interpreted as an octal number. You're also mentioning years. If you're trying to manipulate dates, then don't use ints. Use a library like Joda time. I assume you need something like:

String string = "09asdasdas";
String dateString = string.substring(0, 2);
DateTimeFormatter formatter = DateTimeFormat.forPattern("YY");
DateTime date = formatter.parseDateTime(dateString);  
System.out.println(date);


Your best bet is probably to check the first character and if 0, trim it and then send to Integrer.parseInt() - if I remember correctly, Integer.parseInt doesn't like a number of factors (leading 0s, being among them) I'd just remove it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜