1. Introduction
1.导言
Often, when working with several programming scenarios, there will be strings that contain numbers, and it might be necessary to find the greatest among these values.
在处理多个编程场景时,经常会有 字符串包含 数字,因此可能需要在这些值中找出最大值。
In this tutorial, we’ll delve into different ways and Java code illustrations for properly identifying and extracting the greatest numeric value from a given string.
在本教程中,我们将深入探讨从给定字符串中正确识别和提取最大数值的不同方法和 Java 代码示例。
2. String Parsing with Comparison
2.带比较功能的字符串解析
The simplest method includes reading the strings and identifying the numeric substrings. We can detect the largest number through a comparison of the prefixes. Let’s take an example:
最简单的方法包括读取字符串并识别数字子串。我们可以通过比较前缀来检测最大的数字。让我们举个例子:
String inputString = "The numbers are 10, 20, and 5";
int expectedLargestNumber = 20;
@Test
void givenInputString_whenUsingBasicApproach_thenFindingLargestNumber() {
String[] numbers = inputString.split("[^0-9]+");
int largestNumber = Integer.MIN_VALUE;
for (String number : numbers) {
if (!number.isEmpty()) {
int currentNumber = Integer.parseInt(number);
if (currentNumber > largestNumber) {
largestNumber = currentNumber;
}
}
}
assertEquals(expectedLargestNumber, largestNumber);
}
Here, we first use the split() method to split the input string named inputString into an array of sub-strings. Such division takes place through a regular expression, [^0-9]+, that intercepts only digits in the string.
在这里,我们首先使用 split() 方法将名为 inputString 的输入字符串分割成一个子字符串数组。这种分割是通过正则表达式 [^0-9]+ 进行的,该表达式只截取字符串中的数字。
Subsequently, a regular loop illustrates the string splitting. The loop restricts the array to having the resulting substrings and, on purpose, no empty strings. The implementation of each non-empty substring contains a prominent conversion with the Integer.parseInt() method.
随后,一个正则表达式循环对字符串拆分进行了说明。该循环限制数组只能有结果子串,而且不能有空字符串。每个非空子串的实现都包含使用 Integer.parseInt() 方法进行的突出转换。
Afterwards, a comparison between the current numeric value and the largestNumber found so far takes place, and an update happens in case a larger value is encountered. Finally, we use the assertEquals() method to ensure that the largestNumber is equal to the expectedLargestNumber.
随后,我们将比较当前数值和迄今为止找到的 largestNumber 数值,如果遇到更大的数值,则进行更新。最后,我们使用 assertEquals() 方法确保 largestNumber 与 expectedLargestNumber 相等。
3. Efficient Numeric Extraction with Regular Expressions
3.使用正则表达式高效提取数字
Regular expressions are the ones that allow us to extract the numeric values from a string concisely and effectively. Taking advantage of the Pattern and Matcher classes, we thus make the process more streamlined. Here’s a simple example:
正则表达式允许我们简洁有效地从字符串中提取数值。利用 Pattern 和 Matcher 类,我们可以使提取过程更加简洁。下面是一个简单的例子:
@Test
void givenInputString_whenUsingRegularExpression_thenFindingLargestNumber() {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(inputString);
int largestNumber = Integer.MIN_VALUE;
while (matcher.find()) {
int currentNumber = Integer.parseInt(matcher.group());
if (currentNumber > largestNumber) {
largestNumber = currentNumber;
}
}
assertEquals(expectedLargestNumber, largestNumber);
}
Here, we start by compiling a regular expression (\d+) using the Pattern.compile() method. This expression is meticulously designed to focus on matching one or more digits within the input string.
在此,我们首先使用 Pattern.compile() 方法编译正则表达式 (\d+)。该表达式经过精心设计,主要用于匹配输入字符串中的一个或多个数字。
Then, we initialize the Matcher object, denoted as a matcher, by applying the compiled pattern to the inputString.
然后,我们将编译后的 pattern 应用于 inputString 来初始化 Matcher 对象(表示为 matcher )。
Afterward, we enter a subsequent while loop. The numeric value is extracted within each iteration using the Integer.parseInt(matcher.group()) method. A crucial comparison unfolds, assessing this current numeric value against the existing largestNumber. Should a larger value be discovered, the largestNumber is promptly updated to reflect this identification.
之后,我们进入后续的 while 循环。每次迭代都会使用 Integer.parseInt(matcher.group()) 方法提取数值。关键的比较将展开,将当前数值与现有的 largestNumber 进行评估。如果发现更大的数值,largestNumber 会立即更新以反映这一识别结果。
4. Stream and Lambda Expressions
4.流和 Lambda 表达式
Java 8 proposes the Stream API and lambda expression; therefore, the code is more compact and easier-to-read.
Java 8 提出了 Stream API 和 lambda 表达式;因此,代码更加紧凑,更易于阅读。
Let’s take a simple implementation:
让我们来做一个简单的实验:
@Test
void givenInputString_whenUsingStreamAndLambdaExpression_thenFindingLargestNumber() {
int largestNumber = Arrays.stream(inputString.split("[^0-9]+"))
.filter(s -> !s.isEmpty())
.mapToInt(Integer::parseInt)
.max()
.orElse(Integer.MIN_VALUE);
assertEquals(expectedLargestNumber, largestNumber);
}
In this test method, we begin by filtering the string to extract its numeric components exclusively, which is achieved through the utilization of the split() method. Additionally, we incorporate measures to address the potential occurrence of an empty stream, implementing the isEmpty() method.
在此测试方法中,我们首先对字符串进行过滤,只提取其数字部分,这是通过使用 split() 方法实现的。此外,我们还使用 isEmpty() 方法来解决可能出现的空流问题。
Following the initial filtering, we leverage the mapToInt() method to systematically convert each non-empty substring into an integer, facilitated by the Integer::parseInt reference. Subsequently, the max() operation efficiently identifies the largest integer value present within the processed stream.
在进行初始过滤后,我们利用 mapToInt() 方法将每个非空子串系统地转换为整数,Integer::parseInt 引用为这一转换提供了便利。随后,max() 操作将有效识别已处理流中存在的最大整数值。
We employ the orElse() method to wrap up the streamlined approach, strategically setting the default value to Integer.MIN_VALUE.
我们使用 orElse() 方法来总结简化方法,战略性地将默认值设置为 Integer.MIN_VALUE 。
5. Conclusion
5.结论
In conclusion, this tutorial is a thorough examination of techniques that make it easier to work with strings containing numbers in Java.
总之,本教程深入探讨了如何在 Java 中更轻松地处理包含数字的字符串。
As always, the complete code samples for this article can be found over on GitHub.
与往常一样,本文的完整代码示例可在 GitHub 上找到。