Skip to content

Commit

Permalink
Extract integers from string
Browse files Browse the repository at this point in the history
  • Loading branch information
AnghelLeonard committed Feb 22, 2020
1 parent 6beaeaf commit 132d0d3
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public static List<Integer> extract(String str) {
}

List<Integer> result = new ArrayList<>();
StringBuilder temp = new StringBuilder(String.valueOf(Integer.MAX_VALUE).length());
StringBuilder temp = new StringBuilder(
String.valueOf(Integer.MAX_VALUE).length());

for (int i = 0; i < str.length(); i++) {

Expand Down
14 changes: 14 additions & 0 deletions Chapter10/ExtractSurrogatePairs/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coding.challenge</groupId>
<artifactId>ExtractIntegers</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
<name>ExtractIntegers</name>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package coding.challenge;

public class Main {

public static void main(String[] args) {

String str = "cv dd 4 k 2321 2 11 k4k2 66 4d";

System.out.println("String: " + str);
System.out.println("Integers : " + Strings.extract(str));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package coding.challenge;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class Strings {

private Strings() {
throw new AssertionError("Cannot be instantiated");
}

public static List<Integer> extract(String str) {

if (str == null || str.isBlank()) {
return Collections.emptyList();
}

List<Integer> result = new ArrayList<>();
StringBuilder temp = new StringBuilder(String.valueOf(Integer.MAX_VALUE).length());

for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

if (Character.isDigit(ch)) { // or, if (((int) ch) >= 48 && ((int) ch) <= 57)
temp.append(ch);
} else {
if (temp.length() > 0) {
result.add(Integer.parseInt(temp.toString()));
temp.delete(0, temp.length());
}
}
}

return result;
}
}

0 comments on commit 132d0d3

Please sign in to comment.