Converting string to int using C#

后端 未结 4 1504
日久生厌
日久生厌 2020-12-12 01:48

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 ASCI

相关标签:
4条回答
  • 2020-12-12 01:55

    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)
    
    0 讨论(0)
  • 2020-12-12 02:03

    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);
    }
    
    0 讨论(0)
  • 2020-12-12 02:11

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

    0 讨论(0)
  • 2020-12-12 02:14

    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.

    0 讨论(0)
提交回复
热议问题