3

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?

5
  • 3
    SO needs to reject any question that contains the string "wanna" Commented Jun 25, 2010 at 5:04
  • +1 @Michael. I still have no clue what the real question is, just gave a stab at it based on the title itself. Commented Jun 25, 2010 at 5:07
  • I fear you are doing things too complicated. To verify a name doesn't contain numbers you could just use the string.contains() method for example Commented Jun 25, 2010 at 5:08
  • Another +1 from me. I had a stab based on the content of the message instead. :) Commented Jun 25, 2010 at 5:08
  • +1 from me, the question is legit, the title is misleading. Commented Jun 25, 2010 at 5:29

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.)

1 Comment

+1 for the name check, although I'd personally use a regex for it.
0

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);
}

Comments

-1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.