如何将包含随机字符的String转换为有意义的整数数组?
int MAX= 27;
我有字符串input="-3,5,7-12,20-16,21-";
如何将其转换为[1,2,3,5,7,8,9,10,11,12,20,19,18,17,16,21,22,23... MAX ]
(不使用任何输入功能,如input.split(","))
package Others;
import java.util.ArrayList;
import java.util.List;
public class convertToInteger {
public static void main(String[] args) {
String numbers = "-3,5,7-12,20-16,21-";
char c[] = numbers.toCharArray();
System.out.println(c.length);
List<Character> list = new ArrayList<Character>();
for (int i = 0; i < c.length; i++) {
// System.out.println(!(c[i] == '3') + "" + c[i]);
if (numbers.charAt(i) == '-' || numbers.charAt(i) == ',') {
}
else {
int temp = c[i];
int actual = (int) c[i];
if (temp == actual) {
System.out.println("Integer" + c[i]);
if (!((c[i + 1]) == ',')) {
}
}
// System.out.println(c[i]);
}
}
System.out.println(list);
}
}
答案 0 :(得分:0)
如果我理解你的问题,你可以按照
这样做import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class Test {
private static final String NUMBER_ONLY_REGEX = "\\d+";
private static final Pattern REGEX = Pattern.compile("(,|-)");
public static void main(final String[] args) {
final String numbers = "-3,5,7-12,20-16,21-";
final String[] matcher = REGEX.split(numbers);
final List<Integer> integerList = new ArrayList<Integer>();
for (int i = 0; i < matcher.length; i++) {
if(matcher[i].matches(NUMBER_ONLY_REGEX)) {
integerList.add(Integer.parseInt(matcher[i].trim()));
}
}
System.out.println(integerList);
}
}