C# 测试字符串是否为整数?

发布于 2024-08-11 17:42:06 字数 155 浏览 2 评论 0原文

我只是好奇 C# 语言或 .NET Framework 中是否内置了一些东西来测试某些东西是否是整数

if (x is an int)
   // Do something

在我看来可能有,但我只是一年级编程学生,所以我不知道。

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 is an int)
   // Do something

It seems to me that there might be, but I am only a first-year programming student, so I don't know.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

凤舞天涯 2024-08-18 17:42:06

使用 int.TryParse 方法。

string x = "42";
if(int.TryParse(x, out int value))
  // Do something

如果成功解析,它将返回 true,并且输出结果将具有整数值。

Use the int.TryParse method.

string x = "42";
if(int.TryParse(x, out int value))
  // Do something

If it successfully parses it will return true, and the out result will have its value as an integer.

从此见与不见 2024-08-18 17:42:06

如果您只想检查传递变量的类型,您可能可以使用:

    var a = 2;
    if (a is int)
    {
        //is integer
    }
    //or:
    if (a.GetType() == typeof(int))
    {
        //is integer
    }

If you just want to check type of passed variable, you could probably use:

    var a = 2;
    if (a is int)
    {
        //is integer
    }
    //or:
    if (a.GetType() == typeof(int))
    {
        //is integer
    }
山色无中 2024-08-18 17:42:06

我想我记得看过 int.TryParse 和 int.Parse Regex 之间的性能比较,并且 char.IsNumber 和 char.IsNumber 是最快的。无论如何,无论性能如何,这里还有另一种方法可以做到这一点。

        bool isNumeric = true;
        foreach (char c in "12345")
        {
            if (!Char.IsNumber(c))
            {
                isNumeric = false;
                break;
            }
        }

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;
            }
        }
扛刀软妹 2024-08-18 17:42:06

对于 Wil P 解决方案(见上文),您还可以使用 LINQ。

var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);

For Wil P solution (see above) you can also use LINQ.

var x = "12345";
var isNumeric = !string.IsNullOrEmpty(x) && x.All(Char.IsDigit);
夏日落 2024-08-18 17:42:06

如果您只想检查它是否是字符串,则可以将“out int”关键字直接放置在方法调用中。根据 dotnetperls.com 网站,旧版本的 C# 不允许使用此语法。通过这样做,您可以减少程序的行数。

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
}

如果你还想获取int值,可以这样写。

方法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
}

方法2

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

参考:https://www.dotnetperls .com/parse

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

舞袖。长 2024-08-18 17:42:06

它很简单...使用这段代码,

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

如果您的字符串有整数,它将返回 true,否则返回 false...

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

音盲 2024-08-18 17:42:06

此函数将告诉您字符串是否仅包含字符 0123456789。

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

这与 int.TryParse() 不同,后者会告诉您字符串是否可以是整数。
例如。 " 123\r\n" 将从 int.TryParse() 返回 TRUE,但从上述函数返回 FALSE。

...仅取决于您需要回答的问题。

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.

那些过往 2024-08-18 17:42:06
private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

我前段时间写的一些东西。上面有一些很好的例子,但只值我的 2 美分。

private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Something I wrote a while back. Some good examples above but just my 2 cents worth.

是你 2024-08-18 17:42:06

也许这可以是另一种解决方案

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();

Maybe this can be another solution

try
{
    Console.Write("write your number : ");
    Console.WriteLine("Your number is : " + int.Parse(Console.ReadLine()));
}
catch (Exception x)
{
    Console.WriteLine(x.Message);
}
Console.ReadLine();
风透绣罗衣 2024-08-18 17:42:06

我已经编码了大约两周,并创建了一个简单的逻辑来验证整数是否已被接受。

    Console.WriteLine("How many numbers do you want to enter?"); // request a number
    string input = Console.ReadLine(); // set the input as a string variable
    int numberTotal; // declare an int variable

    if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
    {
        while (numberTotal  < 1) // numberTotal is set to 0 by default if no number is entered
        {
            Console.WriteLine(input + " is an invalid number."); // error message
            int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
        }

    } // this loop will repeat until numberTotal has an int set to 1 or above

如果您愿意不将操作声明为循环的第三个参数,也可以在 FOR 循环中使用上述内容,例如

    Console.WriteLine("How many numbers do you want to enter?");
    string input2 = Console.ReadLine();

    if (!int.TryParse(input2, out numberTotal2))
    {
        for (int numberTotal2 = 0; numberTotal2 < 1;)
        {
            Console.WriteLine(input2 + " is an invalid number.");
            int.TryParse(Console.ReadLine(), out numberTotal2);
        }

    }

如果您不需要循环,只需删除整个循环大括号即可

I've been coding for about 2 weeks and created a simple logic to validate an integer has been accepted.

    Console.WriteLine("How many numbers do you want to enter?"); // request a number
    string input = Console.ReadLine(); // set the input as a string variable
    int numberTotal; // declare an int variable

    if (!int.TryParse(input, out numberTotal)) // process if input was an invalid number
    {
        while (numberTotal  < 1) // numberTotal is set to 0 by default if no number is entered
        {
            Console.WriteLine(input + " is an invalid number."); // error message
            int.TryParse(Console.ReadLine(), out numberTotal); // allows the user to input another value
        }

    } // this loop will repeat until numberTotal has an int set to 1 or above

you could also use the above in a FOR loop if you prefer by not declaring an action as the third parameter of the loop, such as

    Console.WriteLine("How many numbers do you want to enter?");
    string input2 = Console.ReadLine();

    if (!int.TryParse(input2, out numberTotal2))
    {
        for (int numberTotal2 = 0; numberTotal2 < 1;)
        {
            Console.WriteLine(input2 + " is an invalid number.");
            int.TryParse(Console.ReadLine(), out numberTotal2);
        }

    }

if you don't want a loop, simply remove the entire loop brace

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文