我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
基于上一个示例,我创建了一个方法:
private string GetNumberFromString(string sLongString, int iLimitNumbers)
{
string sReturn = "NA";
int iNumbersCounter = 0;
int iCharCounter = 0;
string sAlphaChars = string.Empty;
string sNumbers = string.Empty;
foreach (char str in sLongString)
{
if (char.IsDigit(str))
{
sNumbers += str.ToString();
iNumbersCounter++;
if (iNumbersCounter == iLimitNumbers)
{
return sReturn = sNumbers;
}
}
else
{
sAlphaChars += str.ToString();
iCharCounter++;
// reset the counter
iNumbersCounter = 0;
}
}
return sReturn;
}
其他回答
遍历字符串并使用Char。IsDigit
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
使用正则表达式…
Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");
if (m.Success)
{
Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
Console.WriteLine("You didn't enter a string containing a number!");
}
你可以像下面这样使用String属性:
return new String(input.Where(Char.IsDigit).ToArray());
它只给出字符串中的数字。
string input = "Hello 20, I am 30 and he is 40";
var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
\d+是整数的正则表达式。所以
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
返回subjectString中第一个数字出现的字符串。
Int32.Parse(resultString)会给你一个数字。