Boa*_*rdy 15 c# string substring
我目前正在使用C#开发一个应用程序,我需要在字符串中的某个字符后获取子字符串.
else if (txtPriceLimit.Text.Contains('.') && char.IsNumber(e.KeyChar))
{
int index = txtPriceLimit.Text.IndexOf('.');
string pennies = txtPriceLimit.Text.Substring(index, txtPriceLimit.Text.Length);
Console.WriteLine("Pennies: " + pennies);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,它一直在想出一个IndexOutOfRangeException.如何从索引到结尾获取字符串的内容?
感谢您的任何帮助,您可以提供.
编辑: 刚刚发现我已经尝试的各种事情似乎确实有效,除了它没有从最后一个按钮获取值到文本字段.我正在使用KeyPress事件来执行此操作.
例如,如果我输入.123,它将只打印12.然后,如果我在末尾添加4,它将打印123
Don*_*nut 28
您正在使用的重载String.Substring采用起始索引和指定长度.作为起始索引,您使用的是" ." 的位置,但作为长度,您使用的是整个字符串的长度.如果index是大于0,这将导致异常(如您所见).
相反,只需使用:
string pennies = txtPriceLimit.Text.Substring(index + 1);
Run Code Online (Sandbox Code Playgroud)
这将获得位于" " txtPriceLimit.Text 之后的所有字符..请注意,我们需要在索引中添加1; 否则" ."将包含在结果子字符串中.