我的问题是我想提取字符串中的第一个数字。 字符串的格式就是这样
string text = "Board the DT line, go 1 stops toward Test";
我想要的是值1。这就是我试图做到的方式
int digit1 = int.Parse(text.Substring(text.IndexOf("go")+1, text.IndexOf("stops")-1));
我得到的错误是mscorlib.dll中发生了'System.FormatException'类型的未处理异常
其他信息:输入字符串的格式不正确。
答案 0 :(得分:1)
如果您是编程的新手,您可能希望将其分解为较小的任务。
例如,您可以首先对子字符串值进行硬编码以确保获得正确的结果
var str = "Board the DT line, go 1 stops toward Test";
var number = str.Substring(22, 1);
当您知道正确的数字时,可以查看如何以编程方式获取这些值。
var index = str.IndexOf("go "); //gives you 19
var index = str.IndexOf("go ") + 3 //add 3 to get the start index
然后用硬编码值代替代码
var number = str.Substring(str.IndexOf("go ") + 3, 1);
答案 1 :(得分:0)
您还可以使用正则表达式:[0-9]+
。此模式提取字符串中的所有数字。
var matches = Regex.Matches("Board the DT line, go 1 stops toward Test", "[0-9]+");
foreach(Match match in matches)
{
int number = int.Parse(match.Value);
Console.WriteLine(number);
}