BreakTheCode
BreakTheCode

Reputation: 51

Java Program to get the sum of integers present in a string considering one of the integers is present in extreme end

I want to get the sum of integers present in the String "abc22gh20fg4". I want my output as 22+20+4=46.

I have written the code as below but it gives 22+20=44. It is not considering the number present in the very end.

public static void main(String[] args) {

    String str = "abc22gh20fg4";
    String num = "";
    int sum = 0;
    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            num = num + str.charAt(i);
        } else {
            if (!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}

Upvotes: 0

Views: 212

Answers (4)

soorapadman
soorapadman

Reputation: 4509

I would go with split instead of deep for loop :

    String str = "abc22gh20fg4";
    String regex = "[^\\d]+"; // this will extract only digit
    String[] strs = str.split(regex);
    int sum = Arrays.stream(strs)
            .filter(digits -> digits != null && !digits.equals(""))
            .mapToInt(Integer::parseInt).sum();

    System.out.println(sum);

If you want before java 8

    String str = "abc22gh20fg4";
    String regex = "[^\\d]+";
    String[] strs = str.split(regex); // this will extract only digit 
    int sum = 0;
    for (String digits:strs) { // iterate each digits
        if (digits!=null && !digits.equals("")){ // check null or empty
            sum += Integer.parseInt(digits); // parse and sum
        }
    }

    System.out.println(sum);

Update:

Your actual problem is when you loop through all the character the last character is number . it exit the loop without sum so you need to check if it is last digit sum it .

public class Test {
    public static void main(String[] args) {

        String str = "abc22gh20fg4";
        String num = "";

        int sum = 0;
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                num = num + str.charAt(i);

                if (i==str.length()-1){ // check if it is last 
                    sum = sum + Integer.parseInt(num);
                }

            } else {
                if (!num.equals("")) {
                    sum = sum + Integer.parseInt(num);
                    num = "";
                }
            }
        }
        System.out.println(sum);
    }
}

Upvotes: 1

Mahdi Khardani
Mahdi Khardani

Reputation: 52

public static void main(String[] args) {

    int totalIntegerValue=0;        
    String currentStringValue="";
    String totalStringValue="";
    Scanner s = new Scanner(System.in);
    String input = s.nextLine();
    for(int i=0; i<input.length(); i++) {
        if(Character.isDigit(input.charAt(i))) {
            currentStringValue+=input.charAt(i);
            totalIntegerValue+=Integer.parseInt(currentStringValue);
            totalStringValue+=currentStringValue+"+";
        }
        else
        {           
            currentStringValue="";
        }
    }
    System.out.println(totalStringValue.substring(0, totalStringValue.length()-1)+"="+totalIntegerValue);
    s.close();
}

Upvotes: 0

nissim abehcera
nissim abehcera

Reputation: 831

Append this line if character is digit

  sum=sum+Integer.parseInt(num); one more time just after for loop

Upvotes: 0

thibsc
thibsc

Reputation: 4049

You can iterate on integer by using regex:

String str = "abc22gh20fg4";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
int sum = 0;
while (m.find()) {
    sum += Integer.parseInt(m.group());
}
System.out.println(sum); // Output: 46

Upvotes: 0

Related Questions