Question:
Program to remove special characters and print sum of print sum of the unique numerical characters in the given string
Input: 123%#$.257
Output: Sum: 18
Program:
import java.io.*;
public class LetUsCodeinC{
public static void main(String[ ] args){
String inpStr = "123%#$.257";
//Removing special characters from the given string
inpStr = inpStr.replaceAll("[^0-9]","");
String resStr = "";
int sum = 0;
//Removing duplicates from the resStr String
for(int i = 0; inpStr.length( ); i++){
if(!resStr.contains(String.valueOf(inpStr.charAt(i)))){
resStr += String.valueOf(inpStr.charAt(i));
}
}
//Sum of all the numeric characters of resStr.
for(int i = 0; resStr.length( ); i++){
sum += Integer.parseInt(resStr.charAt(i) + "");
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 18
Explanation:
First we need to divide this program into 3 modules.
1. Removing special characters from the given string.
2. Removing duplicates from the resultant string.
3. Sum of all the resultant numeric characters of string.
0 comments:
Post a Comment