如果您只对反转String 感兴趣,而不关心自然顺序,您可以执行类似的操作
String word = "1, 2, 3, 4, 5";
word = word.replace(", ", "");
StringBuilder s = new StringBuilder();
for (int i = 0; i <= word.length() - 1; i++) {
char c = word.charAt(word.length() - i - 1);
if (s.length() > 0) {
s.append(", ");
}
s.append(c);
}
哪个输出5, 4, 3, 2, 1
当然,如果你对保持数字的自然顺序感兴趣,它会变得有点复杂......
//String value = "1, 2, 3, 4, 5";
String value = "1, 5, 4, 3, 2";
System.out.println("Start with " + value);
String parts[] = value.split(", ");
// We need to convert the String values to ints
List<Integer> listOfValues = new ArrayList<Integer>(5);
for (String part : parts) {
listOfValues.add(Integer.parseInt(part));
}
// Allow the API to sort them...
Collections.sort(listOfValues);
StringBuilder sb = new StringBuilder(value.length());
for (Integer part : listOfValues) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(part);
}
System.out.println(sb);
System.out.println(s.toString());
哪些输出
Start with 1, 5, 4, 3, 2
1, 2, 3, 4, 5