0

Examples of the String

131-5923-213
1421-41-4-12-4
1-1

How would I extract the integers into an Array or find the sum of these integers? My code so far goes

int hyphenCount = socialNum.length()-socialNum.replaceAll("-", "").length();

ArrayList<Integer> sum = new ArrayList<Integer>();
for(int i = 0; i < hyphenCount; i++)
{
   //my brain is too small             
}

What I want to do is make a function like the following

public void extractSum(String s)
{
  int outputSum;

  //stuff

  return outputSum;
} 
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Neo W.
  • 1
  • 1

2 Answers2

0

Using Streams you can do:

int sum = Arrays.stream(str.replace("-",  "").split("")).mapToInt(Integer::valueOf).sum();

Which will replace the hyphen and then split each character, parse the integer, and return the sum

Output: (For the String "131-5923-213")

30

If you want the sum of 131 + 5923 + 213 you could do:

int sum = Arrays.stream(str.split("-")).mapToInt(Integer::valueOf).sum();

Which will split on a hyphen, parse the integers, and return the sum

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
0

Apart from @GBlodgett's answer using stream, you could simply run a for loop to calculate the sum.

String string = "131-5923-213";

String[] num = string.split("-");  //<----num[0] = "131" ,num[1]="5923",num[2] = "213"

int hyphenCount = num.length;  //<----it would give you 3 as length

int mySum = 0;   //initialize the sum as 0

for(int i = 0; i < hyphenCount; i++)
{
     mySum+= Integer.parseInt(num[i]); //<---convert the string to an int

}

Output: 6267

suvojit_007
  • 1,690
  • 2
  • 17
  • 23