Description
To Add numbers present in a string check which character is number. If character is a number, Add it else ignore that character.
C/C++
/* C program to Add numbers present in a string */ //Save it as AddDigitsInString.c #include<stdio.h> int main(){ char str[100]; int i, len, x, add=0; printf("Enter a string : "); scanf("%s",str); len = strlen(str); for(i=0;i<len;i++){ x = str[i] - '0'; if(x>=0 && x<=9){ add += x; }else{ continue; } } printf("Addition : %d", add); return 0; }
Input: Enter a string : gja563lk Output: Addition : 14
Java
/* Java program to Add numbers present in a string */ //Save it as AddDigitsInString.java import java.io.*; import java.util.Scanner; public class AddDigitsInString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str; int i, len, x, add=0; System.out.println("Enter a string : "); str = scanner.nextLine(); len = str.length(); for(i=0;i<len;i++){ x = str.charAt(i) - '0'; if(x>=0 && x<=9){ add += x; }else{ continue; } } System.out.println("Addition : " + add); } }
Input: Enter a string : gja563lk Output: Addition : 14
Related Programs
1) Program to Multiply Numbers Present in a String2) Program to remove given number from a string
3) Program to find maximum number of 1s in a substring of a String
4) Count Number of Words in a String
5) Find Occurrence Of Each Word In a Sentence
6) Print All Unique Words Of A String
7) Program To Print Unique Word Of A String Using Set
8) Program to Append one String to another String
9) Program to Compare Two Strings
10) Program to Reverse a String