Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the string into string and integer in java?

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?

like image 213
karthi Avatar asked May 28 '13 08:05

karthi


People also ask

Is there a way to split string in Java?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.


2 Answers

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]).

like image 185
ConcurrentHashMap Avatar answered Oct 04 '22 04:10

ConcurrentHashMap


String st = "abcd1234";
String st1=st.replaceAll("[^A-Za-z]", "");
String st2=st.replaceAll("[^0-9]", "");
System.out.println("String b = "+st1);
System.out.println("Int c = "+st2);

Output

String b = abcd
Int c = 1234
like image 35
chidanand Avatar answered Oct 04 '22 04:10

chidanand