Java: Splitting string variable into a string and integer variables?


Keywords:java 


Question: 

I have looked everywhere but can seem to find a solution. Is it possible to separate a string variable such as "A1" into a string "A" and integer 1 variables?


3 Answers: 

Start parsing from 0 if you see non digit keep adding it to a StringBuffer, as you see digit add the content of StringBuffer to List<String> strings; and same for Digits List<String> numbers

 

If the string length is strictly one letter and the number is only 1 digit, you can use String.split(""), however for a more generic solution you can use regex

Sample Code:

Matcher matcher = Pattern.compile("([a-zA-Z]+)(\\d+)").matcher("variable1121");
if (matcher.matches()) {
    System.out.println(matcher.group(1) + " , " + matcher.group(2));
}

Output:

variable , 1121
 

If you have a string variable such as A1 or ABC123, you can try:

String input = "A1";
String[] array = input.split("(?<=([a-zA-Z]++))");

String str = array[0];
int integer = Integer.parseInt(array[1]);