如何从字符串中获取第一个数字?
示例:我有"1567438absdg345"
我只想得到"1567438"没有"absdg345",我希望它是动态的,得到第一次出现的Alphabet索引并删除它之后的所有内容.
Guf*_*ffa 35
您可以使用TakeWhile扩展方法从字符串中获取字符,只要它们是数字:
string input = "1567438absdg345";
string digits = new String(input.TakeWhile(Char.IsDigit).ToArray());
Run Code Online (Sandbox Code Playgroud)
Bro*_*ass 19
Linq方法:
string input = "1567438absdg345";
string output = new string(input.TakeWhile(char.IsDigit).ToArray());
Run Code Online (Sandbox Code Playgroud)
或正则表达式方法
String s = "1567438absdg345";
String result = Regex.Match(s, @"^\d+").ToString();
Run Code Online (Sandbox Code Playgroud)
^匹配字符串的开头和\d+后面的数字
您可以遍历字符串并测试当前字符是否为数字Char.isDigit.
string str = "1567438absdg345";
string result = "";
for (int i = 0; i < str.Length; i++) // loop over the complete input
{
if (Char.IsDigit(str[i])) //check if the current char is digit
result += str[i];
else
break; //Stop the loop after the first character
}
Run Code Online (Sandbox Code Playgroud)
忘记正则表达式,在某个地方将其创建为辅助函数...
string input = "1567438absdg345";
string result = "";
foreach(char c in input)
{
if(!Char.IsDigit(c))
{
break;
}
result += c;
}
Run Code Online (Sandbox Code Playgroud)