Home > Back-end >  Collect the digits numbers in the decimal number C#
Collect the digits numbers in the decimal number C#

Time:02-15

I want a method to remove the comma from the decimal number and then collect the digits. For example, if the user inputs 1,3 it will remove the comma and collect 1 and 3 together. I mean 1 3 =4. Can I use trim or replace?

public int AddSum(string x1)
{
    string x = x1.Trim();
        
    int n = Convert.ToInt32(x);
    return n;
}

CodePudding user response:

public int AddSum(string x1)
{
    var digitFilter = new Regex(@"[^\d]");        
    return digitFilter.Replace(x1, "").Select(c => int.Parse(c)).Sum();
}

OR

public int AddSum(string x1)
{
    return x1.Where(c => char.IsDigit(c)).Select(c => c - '0').Sum();
}

CodePudding user response:

If you want to iterate over the characters in a string and compute the sum of digits contained therein, it's trivial:

public static int SumOfDigits( string s ) {
  int n = 0;
  foreach ( char c in s ) {
    n  = c >= '0' && c <= '9' // if the character is a decimal digit
      ? c - '0'               // - convert to its numeric value
      : 0                     // - otherwise, default to zero
      ;                       // and add that to 'n'
  }
  return n;
}

CodePudding user response:

It sounds like you want take a comma-separated string of numbers, add the numbers together, then return the result.

The first thing you have to do is use the Split() method on the input string. The Split() method takes an input string splits the string into an array of strings based on a character:

string[] numbers = x1.Split(',');

So now we have an array of strings called numbers that hold each number. The next thing you have to do is create an empty variable to hold the running total:

int total = 0;

The next thing is to create a loop that will iterate through the numbers array and each time, add the number to the running total. Remember that numbers is an array of strings and not numbers. so we must use the Parse() method of int to convert the string to a number:

foreach (string number in numbers)
{
    total  = int.Parse(number);
}

Finally, just return the result:

return total;

Put it all together and you got this:

private static int AddSum(string x1)
{
    string[] numbers = x1.Split(',');
    int total = 0;
    
    foreach (string number in numbers)
    {
        total  = int.Parse(number);
    }
    
    return total;
}

I hope this helps and clarifies things. Keep in mind that this method doesn't do any kind of error checking, so if your input is bad, you'll get an exception probably.

  •  Tags:  
  • c#
  • Related