0

I am trying to parse through the first three characters of a string.

public List<string> sortModes(List<string> allModesNonSorted)
{
     foreach (string s in allModesNonSorted)
     {
         char firstNumber  = s[0];
         char secondNumber = s[1];
         char thirdNumber  = s[2];

         char.IsDigit(firstNumber);
         char.IsDigit(secondNumber);
         char.IsDigit(thirdNumber);

         combinedNumbers = Convert.ToInt16(firstNumber) + Convert.ToInt16(secondNumber) + Convert.ToInt16(thirdNumber);
     }
     return allModesNonSorted;
}

It recognizes each character correctly, but adds on an extra value 53 or 55. Below when I add the numbers, the 53 and 55 are included. Why is it doing this??

Omar
  • 16,329
  • 10
  • 48
  • 66
Agentgreen
  • 31
  • 3
  • 5
    It's not "adding" extra values. The first two characters of the string are '5' and '7', which have Unicode values 53 and 55. Those values are what are being displayed. – Jon Skeet Feb 18 '13 at 19:52

4 Answers4

5

53 is the Unicode value of '5', and 55 is the Unicode value of '7'. It's showing you both the numeric and character versions of the data.

You'll notice with secondNumber you see the binary value 0 and the character value '\0' as well.

If you want to interpret a string as an integer, you can use

int myInteger = int.Parse(myString);

Specifically if you know you always have the format

input = "999 Hz Bla bla"

you can do something like:

int firstSeparator = input.IndexOf(' ');
string frequency = input.Substring(firstSeparator);
int numericFrequency = int.Parse(frequency);

That will work no matter how many digits are in the frequency as long as the digits are followed by a space character.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

53 is the ASCII value for the character '5' 57 is the ASCII value for the character '7'

this is just Visual Studio showing you extra details about the actual values.

You can proceed with your code.

Brocco
  • 62,737
  • 12
  • 70
  • 76
1

Because you're treating them as Characters.

the character '5' is sequentially the 53rd character in ASCII.

the simplest solution is to just subtract the character '0' from all of them, that will give you the numeric value of a single character.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
1

53 and 55 are the ASCII values of the '5' and '7' characters (the way the characters are stored in memory).

If you need to convert them to Integers, take a look at this SO post.

Community
  • 1
  • 1
Qortex
  • 7,087
  • 3
  • 42
  • 59