Skip to content

Commit 02cf2cd

Browse files
committed
add another approach using regular expression
1 parent 66347d5 commit 02cf2cd

File tree

4 files changed

+32
-5
lines changed

4 files changed

+32
-5
lines changed

problems/string/find_sum_from_string.md

Lines changed: 0 additions & 5 deletions
This file was deleted.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
import java.util.Arrays;
3+
import java.util.Scanner;
4+
5+
/**
6+
* this approach use sting method to split string, base on nonNumber string as
7+
* delimiter
8+
*/
9+
class FindSumFromString {
10+
public static void main(String[] args) {
11+
// read string from stdout
12+
Scanner sc = new Scanner(System.in);
13+
String str = sc.nextLine();
14+
15+
System.err.println(sum(str));
16+
}
17+
18+
static int sum(String str) {
19+
String strArr[] = str.split("[^0-9]+");
20+
int sum = 0;
21+
// System.out.println(Arrays.toString(strArr) + str);
22+
for (String numString : strArr) {
23+
sum += Integer.parseInt(numString);
24+
}
25+
return sum;
26+
}
27+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
`03Ju23st 15te5ll10 12me6 3the ti45me 09f567or 06bu7s 23`
2+
3+
From the Given string print sum of the numbers given in the string
4+
5+
`3+23+15+5+10+12+6+3+45+9+567+6+7+23=734`

0 commit comments

Comments
 (0)