这是一个在没有任何外部库的情况下如何做到这一点的示例:
public static void main(String args[]) {
// source String
String delimitedNumbers = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
// split this String by its delimiter, a comma here
String[] delimitedNumbersSplit = delimitedNumbers.split(",");
// provide a data structure that holds numbers (integers) only
List<Integer> numberList = new ArrayList<>();
// for each part of the split list
for (String num : delimitedNumbersSplit) {
// remove all whitespaces and parse the number
int n = Integer.parseInt(num.trim());
// add the number to the list of numbers
numberList.add(n);
}
// then create the representation you want to print
StringBuilder sb = new StringBuilder();
// [Java 8] concatenate the numbers to a String that delimits by whitespace
numberList.forEach(number -> sb.append(number).append(" "));
// then remove the trailing whitespace
String numbersWithoutCommas = sb.toString();
numbersWithoutCommas = numbersWithoutCommas.substring(0, numbersWithoutCommas.length() - 1);
// and print the result
System.out.println(numbersWithoutCommas);
}
请注意,如果您有一个没有空格的列表,则不需要trim()
拆分结果。String
如果您需要PetitParser库,则必须在其文档中查找如何使用它。