Horje
C# Program to Read a String and Find the Sum of all Digits

Given a string, our task is to first read this string from the user then find the sum of all the digits present in the given string.

Examples

Input : abc23d4
Output: 9

Input : 2a3hd5j
Output: 10

Approach:

To reada String and find the sum of all digits present in the string follow the following steps:

  • First of all we read the string from the user using Console.ReadLine() method.
  • Initialize a integer sum with value 0.
  • Now iterate the string till the end.
  • If the character value is greater than or equal to ‘0’ and less than or equal to ‘9’ (i.e. ascii value between 48 to 57) then perform character – ‘0’  (this gives value of character) and add the value to the sum.
  • Now the sum contains the value of sum of all the digits in the strings.

Example:

C#

// C# program to read the string from the user and
// then find the sum of all digits in the string
using System;
  
class GFG{
      
public static void Main()
{
    string str;
    Console.WriteLine("Enter a string ");
    
    // Reading the string from user.
    str = Console.ReadLine();
    int count, sum = 0;
    int n = str.Length;
      
    for(count = 0; count < n; count++)
    {
          
        // Checking if the string contains digits or not
        // If yes then add the numbers to find their sum 
        if ((str[count] >= '0') && (str[count] <= '9'))
        {
            sum += (str[count] - '0');
        }
    }
    Console.WriteLine("Sum = " + sum);
}
}

Output 1:

Enter a string
abc23d4
Sum = 9

Output 2:

Enter a string
2a3hd5j
Sum = 10

Explanation: In the above example, first we read the string and we will iterate each character and check if the character is an integer or not by comparing the ASCII value of the character. If the character is an integer then add the value to the sum. At the end of the iteration, the sum variable will have the total sum of digits in the string.




Reffered: https://www.geeksforgeeks.org


C#

Related
C# Program to Find Greatest Numbers in an Array using WHERE Clause LINQ C# Program to Find Greatest Numbers in an Array using WHERE Clause LINQ
C# Program to Find Sum of Digits of a Number Using Recursion C# Program to Find Sum of Digits of a Number Using Recursion
C# Program to Print Only Those Numbers Whose Value is Less Than Average of all Elements in an Integer Array using LINQ C# Program to Print Only Those Numbers Whose Value is Less Than Average of all Elements in an Integer Array using LINQ
C# Program to Reverse a String without using Reverse() Method C# Program to Reverse a String without using Reverse() Method
C# Program to Find the IP Address of the Machine C# Program to Find the IP Address of the Machine

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10