提取字符串的最后一部分(部分)
Extract The Last Part (Section) of a String
我只需要提取 /
字符后字符串的最后一部分。
我试过 LastIndexOf
,但失败了。
有什么解决办法吗?
尝试
var strDiv2 = tbxAff.Substring(tbxAff.IndexOf(" / "), /*value is missing*/ );
dblDiv2 = Convert.ToDouble(strDiv2);`
你可以省略第二个参数。这将调用 Substring(int)
重载,其中 returns 一个从指定字符位置开始并持续到字符串末尾的子字符串。
string strDiv2 = tbxAff.Text.Substring(tbxAff.Text.IndexOf("/") + 1);
此外,如果您将提取的子字符串解析为双精度,您可能希望排除 /
分隔符。
使用String.Split()
函数:
string[] y = tbxAff.Text.Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);
然后像这样使用它:
string strDiv2 = y[1] // Second Part
dblDiv2 = Convert.ToDouble(strDiv2);
string clientSpnd = textBox1.Text.Substring(textBox1.Text.LastIndexOf(' ') + 1);
这是一个可以进行安全检查的扩展方法:
public static class StringExtensions
{
public static string LastPartOfStringFrom(this string str, char delimiter )
{
if (string.IsNullOrWhiteSpace(str)) return string.Empty;
var index = str.LastIndexOf(delimiter);
return (index == -1) ? str : str.Substring(index + 1);
}
}
我只需要提取 /
字符后字符串的最后一部分。
我试过 LastIndexOf
,但失败了。
有什么解决办法吗?
尝试
var strDiv2 = tbxAff.Substring(tbxAff.IndexOf(" / "), /*value is missing*/ );
dblDiv2 = Convert.ToDouble(strDiv2);`
你可以省略第二个参数。这将调用 Substring(int)
重载,其中 returns 一个从指定字符位置开始并持续到字符串末尾的子字符串。
string strDiv2 = tbxAff.Text.Substring(tbxAff.Text.IndexOf("/") + 1);
此外,如果您将提取的子字符串解析为双精度,您可能希望排除 /
分隔符。
使用String.Split()
函数:
string[] y = tbxAff.Text.Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);
然后像这样使用它:
string strDiv2 = y[1] // Second Part
dblDiv2 = Convert.ToDouble(strDiv2);
string clientSpnd = textBox1.Text.Substring(textBox1.Text.LastIndexOf(' ') + 1);
这是一个可以进行安全检查的扩展方法:
public static class StringExtensions
{
public static string LastPartOfStringFrom(this string str, char delimiter )
{
if (string.IsNullOrWhiteSpace(str)) return string.Empty;
var index = str.LastIndexOf(delimiter);
return (index == -1) ? str : str.Substring(index + 1);
}
}