【问题标题】:Identify if a string is a number识别字符串是否为数字
【发布时间】:2010-10-28 00:19:09
【问题描述】:

如果我有这些字符串:

  1. "abc" = false

  2. "123" = true

  3. "ab2" = false

是否有一个命令,如IsNumeric() 或其他东西,可以识别字符串是否为有效数字?

【问题讨论】:

  • 从他们的例子中你可以看到他们的意思是如果整个字符串代表一个数字。
  • 返回 str.All(Char.IsDigit);
  • str.All(Char.IsDigit) 将声明“3.14”以及“-2”和“3E14”为假。更不用说:“0x10”
  • 这取决于您要检查的号码类型。对于没有分隔符的整数(即十进制数字字符串),此检查有效,并且与接受的答案和 OP 中隐含的答案相同。
  • @Lucas 感谢您的评论,您不知道我尝试将双精度字符串解析为 int 并想知道它为什么失败...

标签: c# string parsing isnumeric


【解决方案1】:
int n;
bool isNumeric = int.TryParse("123", out n);

更新自 C# 7 起:

var isNumeric = int.TryParse("123", out int n);

或者如果你不需要号码你可以discardout 参数

var isNumeric = int.TryParse("123", out _);

var 可以被它们各自的类型替换!

【讨论】:

  • 不过,我会使用 double.TryParse,因为我们想知道它是否代表一个数字。
  • 如果我将字符串作为“-123”或“+123”传递,函数将返回true。我知道整数有正值和负值。但是如果这个字符串来自用户输入的文本框,那么它应该返回 false。
  • 这是一个很好的解决方案,直到用户输入一个超出 -2,147,483,648 到 2,147,483,647 的值,然后这个静默失败
  • 我更喜欢这个检查的扩展方法:public static bool IsNumeric(this string text) { double _out; return double.TryParse(text, out _out); }
  • 最好使用“long.TryParse”,用​​于最长的字符串。例如“2082546844562”是一个数字,但不能被解析为整数。
【解决方案2】:

如果input 是所有数字,这将返回true。不知道它是否比TryParse 更好,但它会起作用。

Regex.IsMatch(input, @"^\d+$")

如果您只想知道它是否有一个或多个数字与字符混合,请不要使用 ^ +$

Regex.IsMatch(input, @"\d")

编辑: 实际上我认为它比 TryParse 更好,因为很长的字符串可能会溢出 TryParse。

【讨论】:

  • 不过,一劳永逸地构建正则表达式会更有效率。
  • @MAXE:我不同意。正则表达式检查非常慢,因此如果考虑性能,通常会有更好的解决方案。
  • 编辑:如果您正在运行数千个这样的参数,您可以添加 RegexOptions.Compiled 作为参数以提高速度Regex.IsMatch(x.BinNumber, @"^\d+$", RegexOptions.Compiled)
  • 也将在负数和.的事情上失败
  • 对于任何需要添加的新手:使用 System.Text.RegularExpressions;在你的视觉工作室类的顶部
【解决方案3】:

你也可以使用:

using System.Linq;

stringTest.All(char.IsDigit);

如果输入字符串是任何类型的字母数字,它将为所有数字返回true(不是float)和false

Test case Return value Test result
"1234" true ✅Pass
"1" true ✅Pass
"0" true ✅Pass
"" true ⚠️Fail (known edge case)
"12.34" false ✅Pass
"+1234" false ✅Pass
"-13" false ✅Pass
"3E14" false ✅Pass
"0x10" false ✅Pass

请注意stringTest 不应为空字符串,因为这将通过数字测试。

【讨论】:

  • 这很酷。不过需要注意的一件事:一个空字符串将作为数字通过该测试。
  • @dan-gph :我很高兴,你喜欢它。是的,你是对的。我已经更新了上面的注释。谢谢!
  • 这也不适用于十进制情况。正确的测试是 stringTest.All(l => char.IsDigit(l) || '.' == l || '-' == l);
  • 感谢您的输入 Salman,要专门检查字符串中的小数,您可以使用 - if (Decimal.TryParse(stringTest2, out value)) { /* Yes, Decimal / } else { / 不,不是小数*/ }
  • Salman,事情没那么简单——这会将..--..-- 作为有效数字传递。显然不是。
【解决方案4】:

这个功能我用过好几次了:

public static bool IsNumeric(object Expression)
{
    double retNum;

    bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
    return isNum;
}

但你也可以使用;

bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false

来自Benchmarking IsNumeric Options


(来源:aspalliance.com


(来源:aspalliance.com

【讨论】:

  • 从 C# 应用程序引用 Microsoft.VisualBasic.dll? eww :P
  • 我使用“IsNumeric”没有问题,效果很好。您还可以看到 TryParse 和 IsNumeric 之间的效率差异很小。请记住,TryParse 是 2.0 中的新功能,在此之前,使用 IsNumeric 比使用任何其他策略更好。
  • 嗯,VB.NET 的 IsNumeric() 内部使用了 double.TryParse(),经过了一些 VB6 兼容性所需的回旋(除其他外)。如果您不需要兼容性,double.TryParse() 使用起来同样简单,并且通过在进程中加载​​ Microsoft.VisualBasic.dll 可以避免浪费内存。
  • 快速说明:如果您设法一劳永逸地构建底层有限状态机,则使用正则表达式会快得多。通常,构建状态机需要 O(2^n),其中 n 是正则表达式的长度,而读取是 O(k),其中 k 是正在搜索的字符串的长度。所以每次重建正则表达式都会引入偏差。
  • @Lucas 实际上,其中有一些非常好的东西,比如完整的 csv 解析器。如果它存在,没有理由不使用它。
【解决方案5】:

这可能是 C# 中的最佳选择。

如果你想知道字符串是否包含整数(整数):

string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);

TryParse 方法将尝试将字符串转换为数字(整数),如果成功,它将返回 true 并将相应的数字放入 myInt。如果不能,则返回 false。

使用其他响应中显示的int.Parse(someString) 替代方案的解决方案有效,但速度要慢得多,因为抛出异常非常昂贵。 TryParse(...) 在版本 2 中被添加到 C# 语言中,在此之前您别无选择。现在您可以这样做了:因此您应该避免使用Parse() 替代方案。

如果要接受十进制数,decimal 类也有一个.TryParse(...) 方法。在上面的讨论中,将 int 替换为 decimal,同样的原则也适用。

【讨论】:

  • 为什么 TryParse 比将所有字符与整数字符进行比较更好?
【解决方案6】:

如果您不想使用 int.Parse 或 double.Parse,您可以自己使用类似的方法:

public static class Extensions
{
    public static bool IsNumeric(this string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c) && c != '.')
            {
                return false;
            }
        }

        return true;
    }
}

【讨论】:

  • 如果它们只表示整数怎么办? '.' 的语言环境呢?是组分隔符,而不是逗号(例如 pt-Br)?负数呢?组分隔符(英文逗号)?货币符号? TryParse() 可以根据需要使用 NumberStyles 和 IFormatProvider 管理所有这些。
  • 哦,是的,我更喜欢 All 版本。我从来没有真正使用过那个扩展方法,好电话。虽然它应该是 s.ToCharArray().All(..)。至于你的第二点,我听到了,这就是为什么如果你不想使用 int.Parse.... (我假设它有更多开销......)
  • 1.3.3.8.5 并不是一个真正的数字,而 1.23E5 是。
  • @BFree:“虽然它应该是 s.ToCharArray().All(..)”——我意识到我已经疯狂地迟到了,但这不是真的。 Every string "is" already a char array。整齐吧?尽管该行缺少char,否则您将收到Member 'char.IsDigit(char)' cannot be accessed with an instance reference; qualify it with a type name instead 错误:.All(c => char.IsDigit(c) || c == '.')) 和@RusselYang - 所有逻辑都有缺陷;问题是您不介意运送哪些错误。 ;^) 但我明白你的意思。
  • @Lucas 我同意 TryParse 处理更多,但有时不需要。我只需要验证我的信用卡号框(只能有数字)。这个解决方案几乎肯定比尝试解析更快。
【解决方案7】:

您始终可以对许多数据类型使用内置的 TryParse 方法,以查看相关字符串是否会通过。

示例。

decimal myDec;
var Result = decimal.TryParse("123", out myDec);

结果将 = True

decimal myDec;
var Result = decimal.TryParse("abc", out myDec);

结果将 = False

【讨论】:

  • 我想我可能在 VB 风格的语法中比 C# 做得更多,但同样的规则适用。
【解决方案8】:

如果您想捕获更广泛的数字,例如 PHP 的 is_numeric,您可以使用以下代码:

// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)

// Finds whether the given variable is numeric.

// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.

// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
    new Regex(  "^(" +
                /*Hex*/ @"0x[0-9a-f]+"  + "|" +
                /*Bin*/ @"0b[01]+"      + "|" + 
                /*Oct*/ @"0[0-7]*"      + "|" +
                /*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" + 
                ")$" );
static bool IsNumeric( string value )
{
    return _isNumericRegex.IsMatch( value );
}

单元测试:

static void IsNumericTest()
{
    string[] l_unitTests = new string[] { 
        "123",      /* TRUE */
        "abc",      /* FALSE */
        "12.3",     /* TRUE */
        "+12.3",    /* TRUE */
        "-12.3",    /* TRUE */
        "1.23e2",   /* TRUE */
        "-1e23",    /* TRUE */
        "1.2ef",    /* FALSE */
        "0x0",      /* TRUE */
        "0xfff",    /* TRUE */
        "0xf1f",    /* TRUE */
        "0xf1g",    /* FALSE */
        "0123",     /* TRUE */
        "0999",     /* FALSE (not octal) */
        "+0999",    /* TRUE (forced decimal) */
        "0b0101",   /* TRUE */
        "0b0102"    /* FALSE */
    };

    foreach ( string l_unitTest in l_unitTests )
        Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );

    Console.ReadKey( true );
}

请记住,值是数字并不意味着它可以转换为数字类型。例如,"999999999999999999999999999999.9999999999" 是一个完全有效的数值,但它不适合 .NET 数值类型(也就是说,不是标准库中定义的类型)。

【讨论】:

  • 这里不想成为一个聪明的亚历克,但这似乎对字符串“0”失败了。我的正则表达式不存在。有一个简单的调整吗?我得到“0”和可能的“0.0”甚至“-0.0”作为可能的有效数字。
  • @SteveHibbert - 每个人都知道“0”不是数字!说真的……调整正则表达式以匹配 0。
  • 嗯,是我,还是“0”仍未被识别为数字?
  • 因为懒惰和不了解正则表达式,我剪切了上面的代码,看起来它包含“0.0”类型更改。我运行了一个测试来检查运行 .IsNumeric() 的字符串“0”是否返回 false。我认为八进制测试对于任何具有两个数字字符的东西都会返回真,其中第一个是零(第二个是零到七),但是对于它自己的一个大的孤独的零会返回假。如果您使用上面的代码测试“0”,您会得到错误吗?抱歉,如果我知道更多正则表达式,我将能够提供更好的反馈。必须阅读。
  • !噢!只需重新阅读您上面的评论,我错过了额外的星号,我只更新了小数行。有了这个,你是对的,“0”IsNumeric。抱歉,非常感谢您的更新,希望它也能帮助其他人。非常感谢。
【解决方案9】:

我知道这是一个旧线程,但没有一个答案真的对我有用——要么效率低下,要么没有封装以便于重用。如果字符串为空或 null,我还想确保它返回 false。 TryParse 在这种情况下返回 true(空字符串在解析为数字时不会导致错误)。所以,这是我的字符串扩展方法:

public static class Extensions
{
    /// <summary>
    /// Returns true if string is numeric and not empty or null or whitespace.
    /// Determines if string is numeric by parsing as Double
    /// </summary>
    /// <param name="str"></param>
    /// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
    /// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
    /// <returns></returns>
    public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
        CultureInfo culture = null)
    {
        double num;
        if (culture == null) culture = CultureInfo.InvariantCulture;
        return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
    }
}

使用简单:

var mystring = "1234.56789";
var test = mystring.IsNumeric();

或者,如果您想测试其他类型的数字,您可以指定“样式”。 因此,要使用指数转换数字,您可以使用:

var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);

或者要测试一个潜在的十六进制字符串,你可以使用:

var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)

可选的“culture”参数的使用方式大致相同。

它的限制是不能转换太大而不能包含在双精度中的字符串,但这是一个有限的要求,我认为如果你使用的数字大于这个,那么你可能需要额外的无论如何,专门的数字处理功能。

【讨论】:

  • 效果很好,除了 Double.TryParse 不支持 NumberStyles.HexNumber。请参阅 MSDN Double.TryParse。在检查 IsNullOrWhiteSpace 之前为什么要 TryParse?如果 IsNullOrWhiteSpace 不是,TryParse 返回 false?
【解决方案10】:

Kunal Noel 答案更新

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

但是,对于这种情况,我们有空字符串将通过该测试,因此,您可以:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

【讨论】:

  • 这是更好的答案,因为它实际上并没有将字符串转换为整数并存在整数溢出的风险。
【解决方案11】:

可以使用 TryParse 判断字符串是否可以解析成整数。

int i;
bool bNum = int.TryParse(str, out i);

布尔值会告诉你它是否有效。

【讨论】:

    【解决方案12】:

    如果你想知道一个字符串是否是一个数字,你总是可以尝试解析它:

    var numberString = "123";
    int number;
    
    int.TryParse(numberString , out number);
    

    请注意,TryParse 返回一个 bool,您可以使用它来检查您的解析是否成功。

    【讨论】:

      【解决方案13】:

      我想这个答案会在所有其他答案之间丢失,但无论如何,这里是。

      我最终通过 Google 回答了这个问题,因为我想检查 string 是否为 numeric,这样我就可以使用 double.Parse("123") 而不是 TryParse() 方法。

      为什么?因为在你知道解析是否失败之前,必须声明一个out 变量并检查TryParse() 的结果是很烦人的。我想使用ternary operator 来检查string 是否为numerical,然后在第一个三元表达式中解析它或在第二个三元表达式中提供一个默认值。

      像这样:

      var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
      

      它只是比:

      var doubleValue = 0;
      if (double.TryParse(numberAsString, out doubleValue)) {
          //whatever you want to do with doubleValue
      }
      

      我为这些案例制作了一对extension methods


      扩展方法一

      public static bool IsParseableAs<TInput>(this string value) {
          var type = typeof(TInput);
      
          var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
              new[] { typeof(string), type.MakeByRefType() }, null);
          if (tryParseMethod == null) return false;
      
          var arguments = new[] { value, Activator.CreateInstance(type) };
          return (bool) tryParseMethod.Invoke(null, arguments);
      }
      

      示例:

      "123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
      

      因为IsParseableAs() 尝试将字符串解析为适当的类型,而不是仅仅检查字符串是否为“数字”,所以它应该是非常安全的。您甚至可以将它用于具有TryParse() 方法的非数字类型,例如DateTime

      该方法使用反射,您最终会调用TryParse() 方法两次,这当然效率不高,但并非所有内容都必须完全优化,有时方便更重要。

      此方法还可用于轻松地将数字字符串列表解析为 double 或其他具有默认值的类型的列表,而无需捕获任何异常:

      var sNumbers = new[] {"10", "20", "30"};
      var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
      

      扩展方法二

      public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
          var type = typeof(TOutput);
      
          var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
              new[] { typeof(string), type.MakeByRefType() }, null);
          if (tryParseMethod == null) return defaultValue;
      
          var arguments = new object[] { value, null };
          return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
      }
      

      此扩展方法可让您将 string 解析为具有 TryParse() 方法的任何 type,它还允许您指定在转换失败时返回的默认值。

      这比在上面的扩展方法中使用三元运算符要好,因为它只进行一次转换。它仍然使用反射...

      示例:

      "123".ParseAs<int>(10);
      "abc".ParseAs<int>(25);
      "123,78".ParseAs<double>(10);
      "abc".ParseAs<double>(107.4);
      "2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
      "monday".ParseAs<DateTime>(DateTime.MinValue);
      

      输出:

      123
      25
      123,78
      107,4
      28.10.2014 00:00:00
      01.01.0001 00:00:00
      

      【讨论】:

      • 我相信您可能已经发明了我见过的最低效的方法之一。您不仅要解析字符串两次(在可解析的情况下),还要多次调用 reflection 函数来执行此操作。而且,最后,您甚至不会使用扩展方法保存任何击键。
      • 感谢您重复我在倒数第二段中自己写的内容。此外,如果您考虑我的最后一个示例,您肯定会使用此扩展方法保存击键。这个答案并不声称是任何问题的某种神奇解决方案,它只是一个代码示例。使用它,或者不使用它。我认为正确使用它很方便。并且包含了扩展方法和反射的例子,也许有人可以借鉴一下。
      • 你试过var x = double.TryParse("2.2", new double()) ? double.Parse("2.2") : 0.0;吗?
      • 是的,但它不起作用。 Argument 2 must be passed with the 'out' keyword 如果你指定 outnew 你会得到 A ref or out argument must be an assignable variable
      • 性能 TryParse 比这里公开的都好。结果: TryParse 8 Regex 20 PHP IsNumeric 30 Reflections TryParse 31 测试代码dotnetfiddle.net/x8GjAF
      【解决方案14】:

      如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,呃,你知道它是一个)。

      • 没有正则表达式和
      • 尽可能使用微软的代码

      你也可以这样做:

      public static bool IsNumber(this string aNumber)
      {
           BigInteger temp_big_int;
           var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
           return is_number;
      }
      

      这将解决通常的问题:

      • 减号 (-) 或加号 (+) 开头
      • 包含小数字符 BigIntegers 不会解析带小数点的数字。 (所以:BigInteger.Parse("3.3") 会抛出异常,TryParse 同样会返回 false)
      • 没有有趣的非数字
      • 涵盖数字大于通常使用的Double.TryParse 的情况

      您必须添加对System.Numerics 的引用,并在您的班级顶部添加 using System.Numerics;(嗯,我猜第二个是奖金:)

      【讨论】:

        【解决方案15】:

        Double.TryParse

        bool Double.TryParse(string s, out double result)
        

        【讨论】:

          【解决方案16】:

          具有 .net 内置函数的最佳灵活解决方案称为 - char.IsDigit。它适用于无限长数字。如果每个字符都是数字,它只会返回 true。我多次使用它,没有任何问题,而且我找到了更容易清洁的解决方案。我做了一个示例方法。它可以使用了。此外,我添加了对 null 和空输入的验证。所以这个方法现在是完全防弹的

          public static bool IsNumeric(string strNumber)
              {
                  if (string.IsNullOrEmpty(strNumber))
                  {
                      return false;
                  }
                  else
                  {
                      int numberOfChar = strNumber.Count();
                      if (numberOfChar > 0)
                      {
                          bool r = strNumber.All(char.IsDigit);
                          return r;
                      }
                      else
                      {
                          return false;
                      }
                  }
              }
          

          【讨论】:

            【解决方案17】:

            试试下面定义的正则表达式

            new Regex(@"^\d{4}").IsMatch("6")    // false
            new Regex(@"^\d{4}").IsMatch("68ab") // false
            new Regex(@"^\d{4}").IsMatch("1111abcdefg")
            new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
            

            【讨论】:

            • 谢谢,这对我来说是完美的解决方案
            • 我需要测试 PIN 的有效性,4 位数字,没有 0:new Regex(@"^[132465798]{4}").IsMatch(pin.Text)
            • 这应该是公认的答案。您不必将字符串转换为数字来执行此操作,因为它太长会溢出。
            • @EpicSpeedy 我的回答太迟了
            【解决方案18】:

            使用 c# 7,您可以内联 out 变量:

            if(int.TryParse(str, out int v))
            {
            }
            

            【讨论】:

              【解决方案19】:

              使用这些扩展方法可以清楚地区分检查字符串是否为数字和字符串是否包含0-9位数字

              public static class ExtensionMethods
              {
                  /// <summary>
                  /// Returns true if string could represent a valid number, including decimals and local culture symbols
                  /// </summary>
                  public static bool IsNumeric(this string s)
                  {
                      decimal d;
                      return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
                  }
              
                  /// <summary>
                  /// Returns true only if string is wholy comprised of numerical digits
                  /// </summary>
                  public static bool IsNumbersOnly(this string s)
                  {
                      if (s == null || s == string.Empty)
                          return false;
              
                      foreach (char c in s)
                      {
                          if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
                              return false;
                      }
              
                      return true;
                  }
              }
              

              【讨论】:

                【解决方案20】:
                public static bool IsNumeric(this string input)
                {
                    int n;
                    if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
                    {
                        foreach (var i in input)
                        {
                            if (!int.TryParse(i.ToString(), out n))
                            {
                                return false;
                            }
                
                        }
                        return true;
                    }
                    return false;
                }
                

                【讨论】:

                  【解决方案21】:

                  希望对你有帮助

                  string myString = "abc";
                  double num;
                  bool isNumber = double.TryParse(myString , out num);
                  
                  if isNumber 
                  {
                  //string is number
                  }
                  else
                  {
                  //string is not a number
                  }
                  

                  【讨论】:

                    【解决方案22】:
                    Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
                    string text = "12.0";
                    var result = rx.IsMatch(text);
                    Console.WriteLine(result);
                    

                    检查字符串是 uint、ulong 还是仅包含数字 one .(dot) 和 digits 样本输入

                    123 => True
                    123.1 => True
                    0.123 => True
                    .123 => True
                    0.2 => True
                    3452.434.43=> False
                    2342f43.34 => False
                    svasad.324 => False
                    3215.afa => False
                    

                    【讨论】:

                      【解决方案23】:

                      在您的项目中引入对 Visual Basic 的引用并使用其 Information.IsNumeric 方法,如下所示,并且能够捕获浮点数和整数,这与上面仅捕获整数的答案不同。

                          // Using Microsoft.VisualBasic;
                      
                          var txt = "ABCDEFG";
                      
                          if (Information.IsNumeric(txt))
                              Console.WriteLine ("Numeric");
                      
                      IsNumeric("12.3"); // true
                      IsNumeric("1"); // true
                      IsNumeric("abc"); // false
                      

                      【讨论】:

                      • 这种方法的一个潜在问题是IsNumeric 对字符串进行字符分析。所以像9999999999999999999999999999999999999999999999999999999999.99999999999 这样的数字将注册为True,即使无法使用标准数字类型来表示这个数字。
                      【解决方案24】:

                      所有答案都是有用的。但是在寻找数值为 12 位或更多的解决方案时(在我的情况下),然后在调试时,我发现以下解决方案很有用:

                      double tempInt = 0;
                      bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
                      

                      结果变量会给你真假。

                      【讨论】:

                        【解决方案25】:

                        这里是 C# 方法。 Int.TryParse Method (String, Int32)

                        【讨论】:

                          【解决方案26】:
                          //To my knowledge I did this in a simple way
                          static void Main(string[] args)
                          {
                              string a, b;
                              int f1, f2, x, y;
                              Console.WriteLine("Enter two inputs");
                              a = Convert.ToString(Console.ReadLine());
                              b = Console.ReadLine();
                              f1 = find(a);
                              f2 = find(b);
                          
                              if (f1 == 0 && f2 == 0)
                              {
                                  x = Convert.ToInt32(a);
                                  y = Convert.ToInt32(b);
                                  Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
                              }
                              else
                                  Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
                              Console.ReadKey();
                          }
                          
                          static int find(string s)
                          {
                              string s1 = "";
                              int f;
                              for (int i = 0; i < s.Length; i++)
                                 for (int j = 0; j <= 9; j++)
                                 {
                                     string c = j.ToString();
                                     if (c[0] == s[i])
                                     {
                                         s1 += c[0];
                                     }
                                 }
                          
                              if (s == s1)
                                  f = 0;
                              else
                                  f = 1;
                          
                              return f;
                          }
                          

                          【讨论】:

                          • 四次投反对票,但没有人说为什么?我想这是因为 TryParse/Parse 会是更好的选择,但不是每个来这里的人都知道。
                          • 你把它弄得太复杂了,甚至 C 程序员都会说“天哪,一定有更简单的方法来写”
                          • 1.没有理由从控制台读取两个数字并添加它们。无论如何,字符串的来源无关紧要,因此根本没有理由从控制台读取任何内容。
                          • 2. f 的变量是不必要的,你可以直接返回 0 或 1 - 如果你想要一个返回,你可以使用三元运算符。 int 也是 find 的错误返回类型,它应该是 bool,你可以返回 s==s1
                          • 3.您将 s 的数字复制到 s1,然后将 s 与 s1 进行比较。这比它需要的要慢得多。另外,即使 c[0]==s[i] 发生了,为什么还要继续内部循环?您是否希望 s[i] 也等于其他数字?
                          猜你喜欢
                          • 2015-05-11
                          • 1970-01-01
                          • 2011-05-26
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多