C# testing to see if a string is an integer?

后端 未结 10 1361
北恋
北恋 2020-11-28 12:00

I\'m just curious as to whether there is something built into either the C# language or the .NET Framework that tests to see if something is an integer

if (x         


        
相关标签:
10条回答
  • 2020-11-28 12:24

    I think that I remember looking at a performance comparison between int.TryParse and int.Parse Regex and char.IsNumber and char.IsNumber was fastest. At any rate, whatever the performance, here's one more way to do it.

            bool isNumeric = true;
            foreach (char c in "12345")
            {
                if (!Char.IsNumber(c))
                {
                    isNumeric = false;
                    break;
                }
            }
    
    0 讨论(0)
  • 2020-11-28 12:25

    its simple... use this piece of code

    bool anyname = your_string_Name.All(char.IsDigit);
    

    it will return true if your string have integer other wise false...

    0 讨论(0)
  • 2020-11-28 12:25

    This function will tell you if your string contains ONLY the characters 0123456789.

    private bool IsInt(string sVal)
    {
        foreach (char c in sVal)
        {
             int iN = (int)c;
             if ((iN > 57) || (iN < 48))
                return false;
        }
        return true;
    }
    

    This is different from int.TryParse() which will tell you if your string COULD BE an integer.
    eg. " 123\r\n" will return TRUE from int.TryParse() but FALSE from the above function.

    ...Just depends on the question you need to answer.

    0 讨论(0)
  • 2020-11-28 12:27

    If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.

    string x = "text or int";
    if (int.TryParse(x, out int output))
    {
      // Console.WriteLine(x);
      // x is an int
      // Do something
    }
    else
    {
      // x is not an int
    }
    

    If you also want to get the int values, you can write like this.

    Method 1

    string x = "text or int";
    int value = 0;
    if(int.TryParse(x, out value))
    {
      // x is an int
      // Do something
    }
      else
    {
      // x is not an int
    }
    

    Method 2

    string x = "text or int";
    int num = Convert.ToInt32(x);
    Console.WriteLine(num);
    

    Referece: https://www.dotnetperls.com/parse

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