diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java new file mode 100644 index 0000000000..ca86208e59 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java @@ -0,0 +1,18 @@ +package com.baeldung.firstocurrenceofaninteger; + +public class FirstOccurrenceOfAnInteger { + + 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)); + } + +} + diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java new file mode 100644 index 0000000000..ab40316708 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.firstocurrenceofaninteger; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +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; + +class FirstOccurrenceOfAnIntegerUnitTest { + + @Test + 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 + void whenUsingScanner_findFirstInteger() { + int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt(); + Assertions.assertEquals(31, i); + } + + @Test + void whenUsingSplit_findFirstInteger() { + String str = "ba31dung123"; + List tokens = Arrays.stream(str.split("\\D+")) + .filter(s -> s.length() > 0).collect(Collectors.toList()); + Assertions.assertEquals(31, Integer.parseInt(tokens.get(0))); + } + + @Test + void whenUsingCustomMethod_findFirstInteger() { + String str = "ba31dung123"; + Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str); + Assertions.assertEquals(31, i); + } + + +}