For example, if I have a string that contains 5, 4, 3, 2, 1, how do i make it so that a new string or how to print out 1, 2, 3, 4, 5? Thanks.
问问题
2013 次
6 回答
1
做这样的事情:
StringBuilder builder = new StringBuilder("3, 2, 1");
System.out.println(builder.reverse());
于 2012-09-28T02:39:37.023 回答
0
你可以这样做:
String values = "5, 4, 3, 2, 1";
values = values.replace(", ", " ,");
StringBuilder sb = new StringBuilder(values);
values = sb.reverse().toString();
System.out.println(values);
输出是:
1, 2, 3, 4, 5
于 2012-09-28T06:44:42.873 回答
0
如果您可以使用内置方法,这是最短的解决方案:
String input = "12345";
String output = new StringBuilder(input).reverse().toString();
如果您需要实现自己的解决方案,这是使用 achar[]
并仅迭代一半输入字符串的有效答案:
String input = "12345";
char[] chars = input.toCharArray();
for (int i = 0, n = chars.length; i < n/2; i++) {
char tmp = chars[i];
chars[i] = chars[n-i-1];
chars[n-i-1] = tmp;
}
String output = new String(chars);
无论哪种方式,输入将被反转:
System.out.println(output);
> 54321
于 2012-09-28T02:34:13.200 回答
0
将字符串转换为字符数组。从字符数组的长度 -1 循环到 0 索引一次打印每个字符。
于 2012-09-28T02:35:04.980 回答
0
如果您只对反转 感兴趣,而不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
于 2012-09-28T02:39:30.147 回答