C# 标识字符串是否为数字
如果我有这些字符串:C# 标识字符串是否为数字,c#,string,parsing,isnumeric,C#,String,Parsing,Isnumeric,如果我有这些字符串: “abc”=false “123”=true “ab2”=false 是否有一个命令,如IsNumeric()或其他命令,可以识别字符串是否为有效数字 int n; bool isNumeric = int.TryParse("123", out n); 更新从7世纪开始: 或者,如果不需要该数字,则可以输出参数 var isNumeric = int.TryParse("123", out _); var s可由其各自的类型替换 对于许多数据类型,您始终可以使用内置的
“abc”
=false
“123”
=true
“ab2”
=false
IsNumeric()
或其他命令,可以识别字符串是否为有效数字
int n;
bool isNumeric = int.TryParse("123", out n);
更新从7世纪开始:
或者,如果不需要该数字,则可以输出参数
var isNumeric = int.TryParse("123", out _);
var s可由其各自的类型替换 对于许多数据类型,您始终可以使用内置的TryParse方法来查看相关字符串是否会通过 例如
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
结果将为真
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
然后Result=False您可以使用TryParse确定字符串是否可以解析为整数
int i;
bool bNum = int.TryParse(str, out i);
布尔值将告诉您它是否有效。如果您想知道字符串是否是数字,您可以尝试解析它:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
请注意,TryParse
返回一个bool
,您可以使用它来检查解析是否成功。
如果您不想使用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;
}
}
这可能是C#中最好的选择 如果要知道字符串是否包含整数(整数): TryParse方法将尝试将字符串转换为数字(整数),如果成功,将返回true并将相应的数字放入myInt中。如果不能,则返回false 使用其他响应中显示的
int.Parse(someString)
替代方案的解决方案可以工作,但速度要慢得多,因为抛出异常非常昂贵TryParse(…)
在第2版中被添加到C语言中,在此之前,您没有选择的余地。现在您可以这样做了:因此,您应该避免使用Parse()
替代方法
如果要接受十进制数,decimal类还有一个
.TryParse(…)
方法。在上面的讨论中,将int替换为decimal,同样的原则也适用。我已经多次使用此函数:
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
从
(来源:)
(来源:)这里是C#方法。
如果
input
为所有数字,则返回true。不知道它是否比TryParse
更好,但它会起作用
Regex.IsMatch(input, @"^\d+$")
如果您只想知道它是否有一个或多个数字与字符混在一起,请不要使用^
+
和$
Regex.IsMatch(input, @"\d")
编辑:
实际上,我认为它比TryParse好,因为很长的字符串可能会溢出TryParse。希望这有帮助
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
//据我所知,我是用一种简单的方式做的
静态void Main(字符串[]参数)
{
a、b串;
int f1,f2,x,y;
Console.WriteLine(“输入两个输入”);
a=Convert.ToString(Console.ReadLine());
b=控制台.ReadLine();
f1=查找(a);
f2=查找(b);
如果(f1==0&&f2==0)
{
x=转换为32(a);
y=转换为32(b);
Console.WriteLine(“两个输入r编号\n以便添加这些文本框为=“+(x+y).ToString());
}
其他的
Console.WriteLine(“一个或两个输入r字符串\n以便这些文本框的串联为=”+(a+b));
Console.ReadKey();
}
静态整型查找(字符串s)
{
字符串s1=“”;
int f;
对于(int i=0;i 对于(int j=0;j,如果您想要捕捉更广泛的数字,比如PHP,您可以使用以下方法:
// 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 );
}
请记住,仅仅因为值是数值,并不意味着它可以转换为数值类型。例如,“9999999999999999999999999999999999.9999999999”
是一个性能有效的数值,但它不适合.NET数值类型(即标准库中未定义的类型).在项目中引入对Visual Basic的引用,并使用其信息。IsNumeric方法如下图所示,能够捕获浮点数和整数,而上面的答案只捕获整数
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
我猜这个答案会在其他答案之间消失,但不管怎样,还是这样
我最后通过Google问了这个问题,因为我想检查字符串是否是数值,这样我就可以使用double.Parse(“123”)
而不是TryParse()
方法
为什么?因为必须声明一个out
变量并检查TryParse()的结果很烦人
在您知道解析是否失败之前。我想使用三元运算符
检查字符串
是否为数值
,然后在第一个三元表达式中解析它或在第二个三元表达式中提供默认值
像这样:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
它只是比:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
我为这些情况制定了一些扩展方法:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
"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
扩展方法一
扩展方法二
输出:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
"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
如果你想检查一个字符串是否是一个数字(我假设它是一个字符串,因为如果它是一个数字,duh,你知道它是一)
- 没有正则表达式和
- 尽可能多地使用微软的代码
你也可以这样做:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
这将解决通常的问题:
- 开始时为负(-)或正(+)
- 包含十进制字符的BigInteger将不会分析带小数点的数字。(因此:
BigInteger.parse(“3.3”)
将引发异常,而相同的TryParse
将返回false)
- 没有有趣的非数字
- 涵盖数字大于通常使用的
Double.TryParse
您必须添加对System.Numerics
的引用,并具有
在你的课堂上使用System.Numerics;
(我想第二个是奖励:)你也可以使用:
stringTest.All(char.IsDigit);
对于所有Nume,它将返回true
"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
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
stringTest.All(char.IsDigit);
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)
if(int.TryParse(str, out int v))
{
}
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;
}
}
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;
}
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
}
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;
}
}
}
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)
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);