Java: Return the sum of the digits present in the given string
Java String: Exercise-95 with Solution
Write a Java program to return the sum of the digits present in the given string. In the absence of digits, the sum is 0.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to calculate the sum of digits in the given string
public int sumOfDigits(String stng) {
int l = stng.length(); // Get the length of the given string
int sum = 0; // Initialize the sum of digits
// Loop through each character of the string
for (int i = 0; i < l; i++) {
// Check if the character at the current index is a digit
if (Character.isDigit(stng.charAt(i))) {
String tmp = stng.substring(i, i + 1); // Get the digit as a substring
sum += Integer.parseInt(tmp); // Convert the digit to integer and add it to the sum
}
}
return sum; // Return the total sum of digits in the string
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
String str1 = "ab5c2d4ef12s"; // Given string
// Display the given string and the sum of its digits
System.out.println("The given string is: " + str1);
System.out.println("The sum of the digits in the string is: " + m.sumOfDigits(str1));
}
}
Sample Output:
The given string is: ab5c2d4ef12s The sum of the digits in the string is: 14
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to find the longest mirror image string at the both ends of a given string.
Next: Write a Java program to create a new string after removing a specified character from a given string except the first and last position.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/string/java-string-exercise-95.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics