C# 中是否有与 JavaScript parseInt 等效的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/975455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an equivalent to JavaScript parseInt in C#?
提问by Doozer Blake
I was wondering if anyone had put together something or had seen something equivalent to the JavaScript parseInt for C#.
我想知道是否有人将某些东西放在一起或看到过类似于 C# 的 JavaScript parseInt 的东西。
Specifically, i'm looking to take a string like:
具体来说,我希望采用如下字符串:
123abc4567890
and return only the first valid integer
并只返回第一个有效整数
123
I have a static method I've used that will return only the numbers:
我有一个我使用过的静态方法,它只返回数字:
public static int ParseInteger( object oItem )
{
string sItem = oItem.ToString();
sItem = Regex.Replace( sItem, @"([^\d])*", "" );
int iItem = 0;
Int32.TryParse( sItem, out iItem );
return iItem;
}
The above would take:
以上将采取:
ParseInteger( "123abc4567890" );
and give me back
还给我
1234567890
I'm not sure if it's possible to do with a regular expression, or if there is a better method to grab just the first integer from the string.
我不确定是否可以使用正则表达式,或者是否有更好的方法来获取字符串中的第一个整数。
采纳答案by leppie
You are close.
你很近。
You probably just want:
你可能只想:
foreach (Match match in Regex.Matches(input, @"^\d+"))
{
return int.Parse(match.Value);
}
回答by Jon Skeet
Here's a complete example. It will throw an exception if you don't give it a valid string - you can change this behaviour by not explicitly throwing an exception in ParseInteger
, and using int.TryParse
instead.
这是一个完整的例子。如果你没有给它一个有效的字符串,它会抛出一个异常 - 你可以通过不在 中显式抛出异常ParseInteger
并使用int.TryParse
来改变这种行为。
Note that it allows a leading - sign as well, but not a leading +. (Again, easy to change.)
请注意,它也允许前导 - 符号,但不允许前导 +。(同样,易于更改。)
Also note that although I've got three test cases for success situations, I haven't got any test cases for failure.
还要注意,虽然我有三个成功情况的测试用例,但我没有任何失败的测试用例。
Finally, it won't match "abc123def". If you want it to, remove the ^ from the regex.
最后,它不会匹配“abc123def”。如果需要,请从正则表达式中删除 ^。
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
Check("1234abc", 1234);
Check("-12", -12);
Check("123abc456", 123);
}
static void Check(string text, int expected)
{
int actual = ParseInteger(text);
if (actual != expected)
{
Console.WriteLine("Expected {0}; got {1}", expected, actual);
}
}
private static readonly Regex LeadingInteger = new Regex(@"^(-?\d+)");
static int ParseInteger(string item)
{
Match match = LeadingInteger.Match(item);
if (!match.Success)
{
throw new ArgumentException("Not an integer");
}
return int.Parse(match.Value);
}
}
回答by nikmd23
You could use this RegEx ("\A\d+") to find numbers at the beginning of a string.
您可以使用此正则表达式 ("\A\d+") 查找字符串开头的数字。
You can then use int.Parse() to convert that string into an actual integer.
然后您可以使用 int.Parse() 将该字符串转换为实际整数。
回答by Lucero
public static int ParseInteger( object oItem )
{
int iItem = 0;
if (oItem != null) {
Int32.TryParse( Regex.Match( oItem.ToString(), @"\d+" ).Value, out iItem );
}
return iItem;
}
回答by Mark
A slight change to Jon Skeet's excellent solution is in order.
对 Jon Skeet 出色的解决方案稍作改动是必要的。
I would change the regex to (as mentioned by Jon):
我会将正则表达式更改为(如 Jon 所述):
@"^([^\d]+)?(+|-)?\d+"
@"^([^\d]+)?(+|-)?\d+"
This allows for the case of leading characters ahead of the first occurrence of a digit
(e.g., asb12354
-> 12354
) and both signed integer cases (e.g. +
or -
)
这允许在第一次出现数字之前的前导字符的情况
(例如asb12354
-> 12354
)和有符号整数情况(例如+
或-
)
回答by Vin.X
You DON'T have to write your own int parse function!!!!
您不必编写自己的 int 解析函数!!!!
I know this thread is pretty old. but there are some simple way to do this:
我知道这个线程已经很老了。但是有一些简单的方法可以做到这一点:
int.Parse(urString);
use short.Parse(urString); //if you want a short
Or: //use those depend on your situation:
或者://使用那些取决于你的情况:
Convert.ToInt16();
Convert.ToInt32();
Convert.ToInt64();
NOTE:
I am answering your Topic Question "Is there an equivalent to JavaScript parseInt in C#?", just give you some idea, NOT write your code for you. You need to first do a filtering on 'Alphabetical Characters', you can do it with Regular Expression or a simple string.Replace, or up to you.
注意:
我正在回答您的主题问题“C# 中是否有与 JavaScript parseInt 等效的东西?”,只是给您一些想法,而不是为您编写代码。您需要先对“字母字符”进行过滤,您可以使用正则表达式或简单的 string.Replace 进行过滤,或者由您决定。
回答by Siim Nelis
int nr = Int32.Parse(yourstring);