How to Split an Integer Number Into Digits in Java – 如何用 Java 将整数拆分为数位

最后修改: 2023年 9月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述</span

When we work with integer numbers in Java, sometimes we need to break them into individual digits for various calculations or data manipulation tasks.

当我们在 Java 中处理整数时,有时需要将其分解为单个数字,以完成各种计算或数据处理任务。

In this tutorial, we’ll explore various approaches to splitting an integer number into its constituent digits using Java.

在本教程中,我们将探讨使用 Java 将整数拆分成其组成数位的各种方法。

2. Introduction to the Problem

2.问题简介</span

As usual, let’s understand the problem through an example. Let’s say we have an integer number:

像往常一样,让我们通过一个例子来理解这个问题。假设我们有一个整数:</span

int THE_NUMBER = 1230456;

Our goal is to break the number into digits in order:

我们的目标是按以下顺序将数字分解成数位:</span

1, 2, 3, 0, 4, 5, 6

For simplicity, this tutorial will primarily concentrate on positive decimal integers. However, depending on specific needs, we might desire to obtain each digit as an Integer, a char, or a String.

为简单起见,本教程将主要关注正十进制整数。不过,根据具体需要,我们可能希望以 整数字符字符串的形式获取每个数字。

Next, let’s explore various approaches to accommodate these different return types.

接下来,让我们探讨一下适应这些不同返回类型的各种方法。

3. Splitting to an Integer List

3.拆分为 整数 列表

First, let’s break the given integer into a list of Integers. That’s to say, we aim to get this list:

首先,我们将给定的整数分解为一个 Integers 列表。也就是说,我们的目标是得到这个列表:

List<Integer> EXPECTED_INT_LIST = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6);

One of the most straightforward approaches is to use a loop to repeatedly divide the number by 10, extracting the reminder in each iteration until the number becomes zero:

最直接的方法之一是 使用循环重复将数字除以 10,在每次迭代中提取提醒值,直到数字变为零

      1230456 / 10 = 123045 Reminder: 6
  |-> 123045 / 10 = 12304 Reminder: 5
  |-> 12304 / 10 = 1230 Reminder: 4
  |-> 1230 / 10 = 123 Reminder: 0
  |-> 123 / 10 = 12 Reminder: 3
  |-> 12 / 10 = 1 Reminder: 2
  |-> 1 / 10 = 0 Reminder: 1

However, as the example above shows, this approach generates the digits in the reverse order. To solve this, we can use LinkedList as a stack and push() the reminder to the stack in each step:

但是,正如上面的示例所示,这种方法生成的数字顺序正好相反。为了解决这个问题,我们可以使用 LinkedList 作为 堆栈,并在每一步中将提示信息 push() 到堆栈中:

int number = THE_NUMBER;
LinkedList<Integer> result = new LinkedList<>();
while (number > 0) {
    result.push(number % 10);
    number /= 10;
}
assertEquals(EXPECTED_INT_LIST, result);

Also, we can use recursion to implement the same idea:

此外,我们还可以使用递归来实现同样的想法

void collectDigits(int num, List<Integer> digitList) {
    if (num / 10 > 0) {
        collectDigits(num / 10, digitList);
    }
    digitList.add(num % 10);
}

Then, we can call the collectDigits() method to get the result:

然后,我们可以调用 collectDigits() 方法来获取结果:

List<Integer> result = new ArrayList<>();
collectDigits(THE_NUMBER, result);
assertEquals(EXPECTED_INT_LIST, result);

If our Java version is Java 9 or later, we can use String.chars() and IntStream to get the digit list:

如果我们的 Java 版本是 Java 9 或更高版本,我们可以使用 String.chars()IntStream 来获取数字列表

String numStr = String.valueOf(THE_NUMBER);
List<Integer> result = numStr.chars().map(Character::getNumericValue).boxed().collect(Collectors.toList());
assertEquals(EXPECTED_INT_LIST, result);

As the code above shows, we first convert the integer to a string. Then, the numStr.chars() method breaks the number string into chars as an IntStreamNext, Character‘s getNumericValue() gets the digits as ints from the char in the IntStream. Finally, we box ints into Integers and collect the result in a list.

如上面的代码所示,我们首先将整数转换为字符串。然后,numStr.chars() 方法将数字字符串分解为字符串,成为 IntStream 方法。接下来,CharactergetNumericValue()IntStream 中的字符获取 ints 的数字。 最后,我们将 box ints 转换为 Integers 并 将结果收集到一个列表中。

4. Splitting to a char Array

4.分割为 char 数组

Sometimes, we’d like to split the given integer into a char[] array:

有时,我们希望将给定的整数拆分为 char[] 数组:

char[] EXPECTED_CHAR_ARRAY = new char[] { '1', '2', '3', '0', '4', '5', '6' };

This task is straightforward, as the standard String class offers toCharArray() to break a string into a char[]What we need to do is simply convert the integer to String and call the toCharArray() method:

这项任务非常简单,因为 标准 String 类提供了 toCharArray() 方法,可将字符串分解为 char[]我们需要做的就是简单地将整数转换为 String 并调用 toCharArray() 方法:

String numStr = String.valueOf(THE_NUMBER);
char[] result = numStr.toCharArray();
assertArrayEquals(EXPECTED_CHAR_ARRAY, result);

Of course, if required, we can convert the array to a list quickly.

当然,如果需要,我们可以快速将数组转换为列表

5. Splitting to a String Array or String List

5.分割为 String 数组或 String 列表

Finally, let’s see how to split an integer into a String[] array or String list:

最后,让我们看看如何将整数拆分为 String[] 数组或 String 列表:

String[] EXPECTED_STR_ARRAY = new String[] { "1", "2", "3", "0", "4", "5", "6" };
List<String> EXPECTED_STR_LIST = Lists.newArrayList("1", "2", "3", "0", "4", "5", "6");

Since we call this operation a “split,” the powerful split() method can help us solve the problem:

由于我们将此操作称为 “分割”,因此功能强大的 split() 方法可以帮助我们解决问题:

String numStr = String.valueOf(THE_NUMBER);
String[] result = numStr.split("(?<=.)");
assertArrayEquals(EXPECTED_STR_ARRAY, result);

As we can see, the code looks pretty compact. The key is the regex pattern we used in the split() function. (?<=.) is a positive lookbehind expression. For example, “(?<=X)a” matches every ‘a‘ that is after a ‘X‘ character.

我们可以看到,代码看起来非常紧凑。关键是我们在 split() 函数中使用的 regex 模式。(?<=.) 是一个 positive lookbehind 表达式。例如,“(?<=X)a” 匹配”X“字符后的所有”a“。

However, we only have (?<=.) in our pattern. This makes the pattern match zero-width. So, split() takes the zero-width “character” after any character as the splitter. It might be easier to understand if we use the ‘#’ character to replace the zero-width “character” in the number string: “1#2#3#0#4#5#6#”. 

但是,我们的模式中只有 (?<=.)这使得模式匹配为零宽度。因此,split() 将任何 字符之后的零宽度 “字符 “作为分割符。如果我们用 “#”字符替换数字字符串中的零宽度 “字符”,可能会更容易理解:“1#2#3#0#4#5#6#”.</em

Further, split() discards the trailing empty elements by default. Therefore, it produces the desired result.

此外,split() 默认会忽略尾部的空元素。因此,它能产生理想的结果。

6. Conclusion

6.结论</span

In this article, we’ve explored multiple methods to break an integer into digits. Furthermore, we’ve seen how to obtain the digits in different types, such as Integer, char, and String, through examples.

在本文中,我们探讨了将整数分解为数位的多种方法。此外,我们还通过示例了解了如何获取不同类型(如 整数字符串字符串)的数位。

As always, the complete source code for the examples is available over on GitHub.

一如既往,示例的完整源代码可在 GitHub 上获取 .