【发布时间】:2011-07-11 05:18:32
【问题描述】:
如何在 c# 中获取字符串中逗号(,)之前的所有元素? 例如 如果我的字符串是说
string s = "a,b,c,d";
然后我想要 d 之前的所有元素,即在最后一个逗号之前。所以我的新字符串喊看起来像
string new_string = "a,b,c";
我尝试过拆分,但我一次只能使用一个特定元素。
【问题讨论】:
如何在 c# 中获取字符串中逗号(,)之前的所有元素? 例如 如果我的字符串是说
string s = "a,b,c,d";
然后我想要 d 之前的所有元素,即在最后一个逗号之前。所以我的新字符串喊看起来像
string new_string = "a,b,c";
我尝试过拆分,但我一次只能使用一个特定元素。
【问题讨论】:
string new_string = s.Remove(s.LastIndexOf(','));
【讨论】:
ArgumentOutOfRangeException 异常!所以一定要检查最后一个索引是否不是-1,或者如果你想保留一个逗号,它是否大于0。
如果您想要在 last 出现之前的所有内容,请使用:
int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
// Handle case with no commas
}
else
{
string beforeLastIndex = input.Substring(0, lastIndex);
...
}
【讨论】:
使用以下正则表达式:"(.*),"
Regex rgx = new Regex("(.*),");
string s = "a,b,c,d";
Console.WriteLine(rgx.Match(s).Groups[1].Value);
【讨论】:
你也可以试试:
string s = "a,b,c,d";
string[] strArr = s.Split(',');
Array.Resize(strArr, Math.Max(strArr.Length - 1, 1))
string truncatedS = string.join(",", strArr);
【讨论】: