samy
samy

Reputation: 41

Converting string to int using C#

I am using C# and I want to convert a string to int to verify name. For example ** or 12 is not a name. I just want to convert the string into ASCII values and then will verify the name. How do I do that?

Upvotes: 3

Views: 2093

Answers (4)

Keketso Ramosedi
Keketso Ramosedi

Reputation: 8

There multiple ways to convert:

try
{
    string num = "100";
    int value;
    bool isSuccess = int.TryParse(num, out value);
    if(isSuccess)
    {
        value = value + 1;
        Console.WriteLine("Value is " + value);
    }
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}

Upvotes: 0

user315772
user315772

Reputation:

From what I understand, you want to verify that a given string represents a valid name? I'd say you should probably provide more details as to what constitutes a valid name to you, but I can take a stab at it. You could always iterate over all the characters in the string, making sure they're letters or white space:

public bool IsValidName(string theString)
{
    for (int i = 0; i < theString.Length - 1; i++)
    {
        if (!char.IsLetter(theString[i]) && !char.IsWhiteSpace(theString[i]))
        {
            return false;
        }
    }
    return true;
}

Of course names can have other legitimate characters, such as apostrophe ' so you'd have to customize this a bit, but it's a starting point from what I understand your question truly is. (Evidently, not all white space characters would qualify as acceptable either.)

Upvotes: 2

EMP
EMP

Reputation: 62031

It's not clear to me what you're trying to do, but you can get the ASCII codes for a string with this code:

System.Text.Encoding.ASCII.GetBytes(str)

Upvotes: -1

drharris
drharris

Reputation: 11204

Converting back and forth is simple:

int i = int.Parse("42");
string s = i.ToString();

If you do not know that the input string is valid, use the int.TryParse() method.

Upvotes: 5

Related Questions