简体   繁体   English

将字符串转换为反向int数组

[英]Convert string to reverse int array

I want to optimize this solution (idiomatically). 我想优化此解决方案(习惯上)。

I have a string containing only integer values. 我有一个仅包含整数值的字符串。 I want to convert this string into reverse int array. 我想将此字符串转换为反向int数组。 The output should be an integer array 输出应为整数数组

Here is my solution: 这是我的解决方案:

private static int[] stringToReversedIntArray(String num) {
    int[] a = new int[num.length()];
    for (int i = 0; i < num.length(); i++) {
        a[i] = Integer.parseInt(num.substring(i, i + 1));
    }
    a = reverse(a);
    return a;
}

/*
 * Reverses an int array
 */
private static int[] reverse(int[] myArray) {
    int[] reversed = new int[myArray.length];
    for (int i = 0; i < myArray.length; i++) {
        reversed[i] = myArray[myArray.length - (i + 1)];
    }
    return reversed;
}

Input: "1256346258"
Output: {8,5,2,6,4,3,6,5,2,1}

Please suggest how to do same. 请建议如何做。

var input = "1256346258";
var result = Arrays
        .stream(new StringBuffer(input).reverse().toString().split(""))
        .map(Integer::parseInt)
        .collect(Collectors.toList());
System.out.println(result);

Since you are extracting one character at a time, using charAt instead of substring makes more sense. 由于您一次提取一个字符,因此使用charAt而不是substring更有意义。

And since you are converting a single character to an int , Character.getNumericValue() makes more sense then parseInt . 而且由于将单个字符转换为int ,所以Character.getNumericValue()parseInt更有意义。

Hence I'd change 因此,我会改变

a[i] = Integer.parseInt(num.substring(i, i + 1));

to

a[i] = Character.getNumericValue(num.charAt(i));

You can also simplify the reverse part as follows if you don't mind using an Integer[] instead of int[] : 如果您不介意使用Integer[]而不是int[]还可以按如下方式简化反面部分:

private static Integer[] stringToReversedIntArray(String num) {
    Integer[] a = new Integer[num.length()];
    for (int i = 0; i < num.length(); i++) {
        a[i] = Character.getNumericValue(num.charAt(i));
    }
    Collections.reverse(Arrays.asList(a));
    return a;
}

If you want to use streams you can do it with something like this: 如果您想使用流,则可以使用以下方法:

Deque<String> deque = num.chars()
   .map(c -> Character.toString((char) c))
   .map(Integer::parseInt)
   .collect(Collector.of(
        ArrayDeque::new,
        (stack, i) -> stack.addFirst(i),
        (s1, s2) -> { s2.addAll(s1); return s2; })); //this combiner won't really be called unless the stream was parallel

Integer[] reversed = deque.toArray(new Integer[deque.size()]);

This loops through the list just once. 这仅循环遍历列表一次。 The Deque can work as a stack, Last In First Out, so each addFirst() will automatically reverse the order since it adds each item to the front not the back of the list. Deque可以作为堆栈addFirst()先出)工作,因此每个addFirst()都会自动颠倒顺序,因为它将每个项目添加到列表的前面而不是列表的后面。 You can convert it to an array afterwards, or use the Deque as is, which is a normal Collection and implements Iterable . 之后,您可以将其转换为数组,或者按原样使用Deque ,这是一个正常的Collection并实现Iterable

As other answers mentioned, you could also simplify it a bit like this, if you are 100% sure you have only digits, because with the simplified version you won't get a NumberFormatException . 正如提到的其他答案一样,如果您100%确信只有数字,也可以将其简化一下,因为使用简化版本时,您将不会获得NumberFormatException

Deque<String> deque = num.chars()
   .map(c -> Character.getNumericValue((char) c))
   .collect(Collector.of(
        ArrayDeque::new,
        (stack, i) -> stack.addFirst(i),
        (s1, s2) -> { s2.addAll(s1); return s2; }));

Integer[] reversed = deque.toArray(new Integer[deque.size()]);

No need to loop 2 times, you can use StringBuilder to reverse a String, and then loop over it to store the result in your int array: 无需循环2次,您可以使用StringBuilder反转字符串,然后在其上循环以将结果存储在int数组中:

  private static int[] stringToReversedIntArray(String num) {
    num = new StringBuilder(num).reverse().toString();
    int[] result = new int[num.length()]; 
    for (int i = 0; i < result.length; i++){
      result[i] = Character.getNumericValue(num.charAt(i)); 
    }
    return result;
  }

Other options would either be to just reverse your for loop and have it count backwards: 其他选择要么只是反转您的for循环,然后将其倒计数:

for(int i = array.length - 1; i >= 0; i--){
  ...
}

Or use the Stream API in recent versions of Java, as has already been mentioned above in a nice example. 或在Java的最新版本中使用Stream API,如上面在一个很好的示例中已经提到的那样。

String str = "123456";
// Reverse String
str = new StringBuilder(str).reverse().toString();
String strArr[] = str.split("(?!^)");
// Convert to Int Array
int[] intarray = java.util.Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();

Erans solution is fine to me, but i dont like the for loop and i prefer if possible the stream api Erans解决方案对我来说很好,但是我不喜欢for循环,如果可能的话,我更喜欢流API

String testString = "1256346258";
IntStream intStream = testString.chars();       
List<Integer> x = intStream.boxed().collect(Collectors.toList());
Collections.reverse(x);
int[] array = x.stream().mapToInt(i -> Character.getNumericValue(i)).toArray();
System.out.println("x: " + Arrays.toString(array));

just wrap it with a nice method... 只是用一个很好的方法来包装它...

Here's a simple solution with a single for loop. 这是一个带有单个for循环的简单解决方案。 You can "reverse" the digits at the same time you extract the numeric values, just by playing a bit with the indexes: 您可以在提取数值的同时“反转”这些数字,只需对索引进行一点操作即可:

private static int[] stringToReversedIntArray(String num) {
    int len = num.length();
    int[] a = new int[len];
    for (int i = 0; i < len; i++) {
        a[i] = Character.getNumericValue(num.charAt(len - i - 1));
    }
    return a;
}

One-liner: 单线:

return IntStream
    .range(0, num.length())
    .map(i -> Character.getNumericValue(num.charAt(num.length() - i - 1)))
    .toArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM