Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#判断一个字符串是否为数字

作者:ˉ吻干迩的'泪   发布日期:2025-11-24   浏览:43

// 判断一个字符串是否为数字的示例代码

using System;

class Program
{
    static void Main()
    {
        string input = "12345"; // 可以替换为任何需要判断的字符串
        bool isNumeric = IsNumeric(input);

        if (isNumeric)
        {
            Console.WriteLine("字符串是数字");
        }
        else
        {
            Console.WriteLine("字符串不是数字");
        }
    }

    static bool IsNumeric(string str)
    {
        // 使用 double.TryParse 方法尝试将字符串转换为数字
        // 如果转换成功,则返回 true,否则返回 false
        return double.TryParse(str, out _);
    }
}

解释说明:

  • IsNumeric 方法使用了 double.TryParse 函数来尝试将字符串转换为数字。如果转换成功,则返回 true,表示该字符串是有效的数字;否则返回 false
  • TryParse 方法不会抛出异常,而是返回一个布尔值,指示转换是否成功。因此它非常适合用于验证字符串是否为数字。
  • 你可以根据需要修改 input 变量的值来测试不同的字符串。

上一篇:c# in

下一篇:c#??

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站