how to split the string into string and integer in java

佐手、 提交于 2019-11-27 14:59:53

问题


I have the String a="abcd1234" and i want to split this into String b="abcd" and Int c=1234 This Split code should apply for all king of input like ab123456 and acff432 and so on. How to split this kind of Strings. Is it possible?


回答1:


You could try to split on a regular expression like (?<=\D)(?=\d). Try this one:

String str = "abcd1234";
String[] part = str.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);

will output

abcd
1234

You might parse the digit String to Integer with Integer.parseInt(part[1]).




回答2:


You can do the next:

  1. Split by a regex like split("(?=\\d)(?<!\\d)")
  2. You have an array of strings with that and you only have to parse it.



回答3:


Use a regular expression:

Pattern p = Pattern.compile("([a-z]+)([0-9]+)");
Matcher m = p.matcher(string);
if (!m.find())
{ 
  // handle bad string
}
String s = m.group(1);
int i = Integer.parseInt(m.group(2));

I haven't compiled this, but you should get the idea.




回答4:


A brute-force solution.

String a = "abcd1234";
int i;
for(i = 0; i < a.length(); i++){
    char c = a.charAt(i);
    if( '0' <= c && c <= '9' )
        break;
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);



回答5:


public static void main(String... s) throws Exception {
        Pattern VALID_PATTERN = Pattern.compile("([A-Za-z])+|[0-9]*");
    List<String> chunks = new ArrayList<String>();
    Matcher matcher = VALID_PATTERN.matcher("ab1458");
    while (matcher.find()) {
        chunks.add( matcher.group() );
    }
}



回答6:


Use regex "[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])" to split the sting by alphabets and numbers.

for e.g.

String str = "ABC123DEF456";

Then the output by using this regex will be :

ABC 123 DEF 456

For full code please visit following url:

http://www.zerotoherojava.com/split-string-by-characters-and-numbers/



来源:https://stackoverflow.com/questions/16787099/how-to-split-the-string-into-string-and-integer-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!