newbie: ToCharArray() problems

  • Thread starter Thread starter Jeff
  • Start date Start date
J

Jeff

IDE: VS .NET 2003
OS: XP pro sp2

this is some line from my code:
string t = "356";
char[] u = t.ToCharArray();

Here I thought u should represent an array of char (the elements 3,5,6) ...
but when I debug the code I see that the elements are: 51'3', 53'5', 54'6'

When I use System.Convert.ToInt32() on the first element (51'3') I get the
value 51, I want it to return 3

What am I doing wrong here?
 
Hi Jeff,

ToCharArray behaves exactly as it is supposed to do, it returns an array of characters, and "356" consists of the characters '3', '5' and '6'.

To my knowledge there isn't a ready made method that returns an array of numbers based on a given string, but you could easily create a method of your own based on ToCharArray and Convert.ToInt32/Int32.Parse

Something like this should work:

int[] StringToIntArray(string s)
{
char[] c = s.ToCharArray();
int[] d = new int[c.Length];
for(int i = 0; i < c.Length; i++)
{
d = Convert.ToInt32(c.ToString());
}
return d;
}



IDE: VS .NET 2003
OS: XP pro sp2

this is some line from my code:
string t = "356";
char[] u = t.ToCharArray();

Here I thought u should represent an array of char (the elements 3,5,6) ...
but when I debug the code I see that the elements are: 51'3', 53'5', 54'6'

When I use System.Convert.ToInt32() on the first element (51'3') I get the
value 51, I want it to return 3

What am I doing wrong here?
 
You're looking at the ASCII numeric equivalents for the characters.

characters are not necessarily numerals therefore casting would not be appropriate. Try this:

static void Main()
{
string s = "123";
char[] cs = s.ToCharArray();
foreach( char c in cs )
{
int i = int.Parse(c.ToString());
Console.WriteLine(i);
}
}

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

IDE: VS .NET 2003
OS: XP pro sp2

this is some line from my code:
string t = "356";
char[] u = t.ToCharArray();

Here I thought u should represent an array of char (the elements 3,5,6) ...
but when I debug the code I see that the elements are: 51'3', 53'5', 54'6'

When I use System.Convert.ToInt32() on the first element (51'3') I get the
value 51, I want it to return 3

What am I doing wrong here?







[microsoft.public.dotnet.languages.csharp]
 
string t = "356";

char[] u = t.ToCharArray();

int i = System.Convert.ToInt32(
u[0].ToString() );
 
Back
Top