Ak C
Ak C

Reputation: 53

char array returning value like 50'w'

Language =C# Software = Visual Studio 2015

While writing program to find sum of integers in given string I am facing issue. while fetching each character from string I am getting value like 87'W',101'e' instead of 'w' ,'e'. (showing respective integer of char also which is not required)

Program:

public static void Main()     
{     
     string s = "Welcome to 2018";     
     int sumofInt = 0;     
       for (int i = 0; i < s.Length; i++)     
       {     
           if (Char.IsDigit(s[i]))     
           {     
               sumofInt += Convert.ToInt32(s[i]);     
           }     
       }     
    Console.WriteLine(sumofInt);     

}   

expected o/p = 11 actual o/p = 203

here for s[i] values are coming as e.g 50'2'

is there any way to avoid this numeric representation of charater (50 , 87 etc) ? ?? (without trimming)

Upvotes: 2

Views: 128

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

The typical trick for '0'..'9' range is to subtract '0':

char digit = '7';
int value = digit - '0';

You can simplify your code with a help of Linq:

public static void Main() {
  string s = "Welcome to 2018";     

  int sumofInt = s.Sum(c => c >= '0' && c <= '9' // do we have digit?
    ? c - '0'                                    // if true, take its value
    : 0);                                        // else 0

  Console.WriteLine(sumofInt);
}  

Upvotes: 0

Mr. Roshan
Mr. Roshan

Reputation: 1805

Try this:-you are getting the ASCII representation of the char as an integer

public static void Main()     
{     
     string s = "Welcome to 2018";     
     int sumofInt = 0;     
       for (int i = 0; i < s.Length; i++)     
       {     
           int val = (int)Char.GetNumericValue(s[i]);
           if (Char.IsDigit(val))     
           {     
               sumofInt += Convert.ToInt32(val);     
           }     
       }     
    Console.WriteLine(sumofInt);     

}   

Upvotes: 1

Related Questions