答案 0 :(得分:-1)
使用以下代码,您可以从字符串中获取数字:
public static void main(String[] args) {
String str = "a2bc45cd5";
Matcher m = Pattern.compile("\\d+").matcher(str);
List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
System.out.println(numbers);
Matcher m1 = Pattern.compile("[A-z]+").matcher(str);
List<String> string = new ArrayList<String>();
while(m1.find()) {
string.add(m1.group());
}
System.out.println(string);
}
//Output :
[2, 45, 5] // For numbers
[a, bc, cd] // For string
使用循环获取数字后,您将获得输出结果。
答案 1 :(得分:-1)
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "a11b4c5";
System.out.println(getAnswerByPassingString(str));
}
public static String getAnswerByPassingString(String str) {
String number = "";
String letter = "";
String resStr = "";
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<String> numbersList = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
char a = str.charAt(i);
if (Character.isDigit(a)) {
number = number + a;
//numbersList.add("" + a);
} else {
letter = letter + a;
stringList.add("" + a);
}
}
Matcher m = Pattern.compile("\\d+").matcher(str);
//List<Integer> numbers = new ArrayList<Integer>();
while(m.find()) {
numbersList.add(""+Integer.parseInt(m.group()));
}
// System.out.println(numbers);
for (int i = 0; i < stringList.size(); i++) {
int j = Integer.parseInt(numbersList.get(i));
String concatStr = stringList.get(i);
int count = 0;
for (int k = 1; k <= j; k++) {
concatStr = concatStr + concatStr;
if (k == j)
count = k;
}
resStr = resStr + concatStr.substring(0, count);
concatStr = "";
}
return resStr;
}
}