Search This Blog

Sunday, September 28, 2025

Sum of Digits in a String

public void sumofdigitsinstring()
{
    string input = "s5s2re6ser38sd0f";
    // Filter out digits, convert them to int, then sum
    int sumOfDigits = input
        .Where(char.IsDigit)         // pick only digits
        .Select(c => Convert.ToInt32(c.ToString()))        // convert char to int (e.g. '3' → 3)
        .Sum();                      // sum all digits
    Console.WriteLine(  "");
}


.Select(c => Convert.ToInt32(c))  // Wont work, because it take ASCII value of char c intead of converting into char c to int values. 

No comments:

Post a Comment