Home  >  Article  >  Backend Development  >  C# program reads string and calculates sum of all numbers

C# program reads string and calculates sum of all numbers

PHPz
PHPzforward
2023-08-27 12:25:051198browse

C# 程序读取字符串并计算所有数字的总和

#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.

Step 1: Read the input 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();

Step 2: Find the sum of the numbers

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());
   }
}

Step 3: Display results

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);

Example

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);
      }
   }
}

Output

The sum of digits in the string is: 27

in conclusion

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete