BAEL-6195
This commit is contained in:
parent
537df5bfdc
commit
04d697ecb2
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.firstoccurrenceofaninteger;
|
||||
|
||||
public class FirstOccurrenceOfAnInteger {
|
||||
|
||||
public static Integer findFirstInteger(String s) {
|
||||
int i = 0;
|
||||
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
int j = i;
|
||||
while (j < s.length() && Character.isDigit(s.charAt(j))) {
|
||||
j++;
|
||||
}
|
||||
return Integer.parseInt(s.substring(i, j));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.firstoccurrenceofaninteger;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
|
||||
class FirstOccurrenceOfAnIntegerTests {
|
||||
|
||||
@Test
|
||||
public void whenUsingPatternMatcher_findFirstInteger() {
|
||||
String s = "ba31dung123";
|
||||
Matcher matcher = Pattern.compile("\\d+").matcher(s);
|
||||
matcher.find();
|
||||
int i = Integer.parseInt(matcher.group());
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingScanner_findFirstInteger() {
|
||||
int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt();
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSplit_findFirstInteger() {
|
||||
String str = "ba31dung123";
|
||||
List<String> tokens = Arrays.stream(str.split("\\D+"))
|
||||
.filter(s -> s.length() > 0).collect(Collectors.toList());
|
||||
Assertions.assertEquals(31, Integer.parseInt(tokens.get(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCustomFunction_findFirstInteger() {
|
||||
String str = "ba31dung123";
|
||||
Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str);
|
||||
Assertions.assertEquals(31, i);
|
||||
}
|
||||
|
||||
|
||||
}
|
Loading…
Reference in New Issue