Home > Blockchain >  Trying to find the sum of all numbers in an alphanumeric string having spaces(i.e. "my12 23name
Trying to find the sum of all numbers in an alphanumeric string having spaces(i.e. "my12 23name

Time:10-16

I have tried with:

public class FindSumOfNumbersInString {

    public static void main(String[] args) {
        
        FindSumOfNumbersInString sum= new FindSumOfNumbersInString();
        
        sum.getNumerics("my12 23name 14 is bijay");
    }
    
    //"my12 23name 14 is bijay"
    
    public void getNumerics(String S) {
        String [] a= S.split(" ");
        int sum=0;
        for(int i=0;i<a.length;i  ) {
            String str=a[i].replaceAll("^0-9","");
             sum=sum Integer.parseInt(str);
            
        }System.out.println(sum);
        
    }

CodePudding user response:

It may be better to look for the strings matching integer numbers \d , then empty strings are not included in the match:

public static void getNumerics(String s) {
    Matcher m = Pattern.compile("\\d ").matcher(s);
    int sum = 0;
    while (m.find()) {
        sum  = Integer.parseInt(m.group(0));
    }
    System.out.println(sum);
}

Similar version using Stream API Matcher::results:

public static void getNumericsStream(String s) {
    int sum = Pattern.compile("\\d ").matcher(s)
            .results()
            .map(MatchResult::group)
            .mapToInt(Integer::parseInt)
            .sum();
    System.out.println(sum);
}

or Scanner::findAll:

public static void getNumericsScanner(String s) {
    int sum = new Scanner(s)
            .findAll("\\d ")
            .map(MatchResult::group)
            .mapToInt(Integer::parseInt)
            .sum();
    System.out.println(sum);
}

Also, the input string may be split by non-digit characters \D and the empty string(s) should be filtered out:

public static void getNumericsSplit(String s) {
    int sum = Arrays.stream(s.split("\\D "))
        .filter(x -> !x.isEmpty())
        .mapToInt(Integer::parseInt)
        .sum();
        
    System.out.println(sum);
}

All these methods print 49 for input "my12 23name 14 is bijay":

getNumerics("my12 23name 14 is bijay");       // 49
getNumericsStream("my12 23name 14 is bijay"); // 49
getNumericsScanner("my12 23name 14 is bijay");// 49
getNumericsSplit("my12 23name 14 is bijay");  // 49

CodePudding user response:

Instead of splitting the string inside the loop, you can split it outside the loop. I also recommend you replace [^0-9\s] with blank. The pattern, [^0-9\s] means non-digits or whitespace. Note the use of [ ] which is used to create character classes and after a pattern is used for one or more occurrences.

Demo:

public class Main {
    public static void main(String[] args) {
        System.out.println(getSumOfNumbers("my12 23name 14 is bijay"));
    }

    static int getSumOfNumbers(String str) {
        String[] a = str.replaceAll("[^0-9\\s]", "").split("\\s ");
        int sum = 0;
        for (int i = 0; i < a.length; i  )
            sum = sum   Integer.parseInt(a[i]);
        return sum;
    }
}

Output:

49
  • Related