I want to split this number based on length : 11101204 . Like Division would be 111. Division2=01,Division3=2,Divison 4=04; i.e., 111, 01 , 12, 04 ...I want it to be split in this way and if the number has only 3 numbers then Division should be 111 and rest should be null How can I achieve this ? Many Thanks !

有帮助吗?

解决方案

Try with String.substring(beginIndex, endIndex)

String string = "11101204";

System.out.println(string.substring(0, 3));
System.out.println(string.substring(3, 5));
System.out.println(string.substring(5, 6));
System.out.println(string.substring(6, 8));

Output:

111
01
2
04

其他提示

Sounds like a job for regular expressions. Your example isn't self-consistent, so you'll have to define your requirements more clearly and adjust the regex to match.

The regex "(\\d{3})(\\d{2})?" would match "111" or "11101", but not "1110" because the second capturing group (what you've called a "division") is not the required two digits. When a string matches, you would use Matcher#group(int) to get the groups. For groups that weren't matched, it will return either null or an empty string depending on whether the expression in the group can match an empty string.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top