Srikanth
Srikanth

Reputation: 683

Convert alphabetic string into Integer in C#

Is it possible to convert alphabetical string into int in C#? For example

string str = "xyz";
int i = Convert.ToInt32(str);

I know it throws an error on the second line, but this is what I want to do.

So how can I convert an alphabetical string to integer?

Thanks in advance

Upvotes: 2

Views: 4376

Answers (3)

Anthony Shaw
Anthony Shaw

Reputation: 8166

To answer the literal questions that you have asked

Is it possible to convert alphabetical string into int in C#?

Simply put... no

So how can I convert an alphabetical string to integer?

You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.

Upvotes: 1

Philip Badilla
Philip Badilla

Reputation: 1058

System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
   return b;
}

this will return each characters ascii value... its up to you what you want to do with them

Upvotes: 3

Matthias
Matthias

Reputation: 12259

You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):

int parsed;
if (!Int32.TryParse(str, out parsed))
   //Do Something

Upvotes: 0

Related Questions