我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
下面是Linq版本:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
其他回答
这是我的算法
//Fast, C Language friendly
public static int GetNumber(string Text)
{
int val = 0;
for(int i = 0; i < Text.Length; i++)
{
char c = Text[i];
if (c >= '0' && c <= '9')
{
val *= 10;
//(ASCII code reference)
val += c - 48;
}
}
return val;
}
使用StringBuilder比在循环中连接字符串的性能稍好一些。如果处理的是大字符串,它的性能要高得多。
public static string getOnlyNumbers(string input)
{
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
if (input[i] >= '0' && input[i] <= '9')
stringBuilder.Append(input[i]);
return stringBuilder.ToString();
}
注意:上面的例子函数只适用于正数
对于那些想要十进制数字的字符串与Regex在两行:
decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);
同样的事情也适用于float, long等等…
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
正则表达式。Split可以从字符串中提取数字。你会得到在字符串中找到的所有数字。
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
输出:
数量:4 数量:40 数量:30 数量:10