Home >Backend Development >C#.Net Tutorial >C# program reads string and calculates sum of all numbers
#C# is a popular object-oriented programming language used for developing Windows applications, web applications, and games. In this article, we will discuss how to write a C# program to read a string and find the sum of all the numbers in the string.
The first step of the program is to read the string entered by the user. We can read a string from the console using the Console.ReadLine() method. Here is an example -
Console.WriteLine("Enter a string:"); string inputString = Console.ReadLine();
The next step is to find the sum of all numbers in the input string. We can use the char.IsDigit() method to check if a character is a number. We can then use the int.Parse() method to convert the numeric character to an integer and add it to the sum.
int sum = 0; foreach (char c in inputString) { if (char.IsDigit(c)) { sum += int.Parse(c.ToString()); } }
Finally, we need to display the sum of the numbers to the user. We can use the Console.WriteLine() method to display the results on the console.
Console.WriteLine("The sum of digits in the string is: " + sum);
This is the complete C# program -
using System; namespace SumOfDigits { class Program { static void Main(string[] args) { string inputString = ("11603529"); int sum = 0; foreach (char c in inputString) { if (char.IsDigit(c)) { sum += int.Parse(c.ToString()); } } Console.WriteLine("The sum of digits in the string is: " + sum); } } }
The sum of digits in the string is: 27
In this article, we learned how to write a C# program to read a string and find the sum of all the numbers in the string. We use the char.IsDigit() method to check if a character is a number, the int.Parse() method to convert a numeric character to an integer, and the Console.WriteLine() method to display the result on the console. This program is very useful in various applications where we need to find the sum of numbers in a given string.
The above is the detailed content of C# program reads string and calculates sum of all numbers. For more information, please follow other related articles on the PHP Chinese website!