c#中字符串中最后一个逗号前的所有元素

doe*_*dos 4 c# string split

如何在逗号(,)之前的所有元素中获取c#中的字符串?例如,如果我的字符串是说

string s = "a,b,c,d";
Run Code Online (Sandbox Code Playgroud)

然后我想要在最后一个逗号之前的所有元素.所以我的新字符串喊出来

string new_string = "a,b,c";
Run Code Online (Sandbox Code Playgroud)

我试过分裂但是我一次只能有一个特定元素.

Jus*_*yes 10

string new_string = s.Remove(s.LastIndexOf(','));
Run Code Online (Sandbox Code Playgroud)

  • 请注意,当原始字符串不包含逗号时,这将引发“ArgumentOutOfRangeException”异常!因此,请务必检查最后一个索引是否不是 -1,或者如果您想保留单个逗号,它是否大于 0。 (2认同)

Jon*_*eet 6

如果您想要在最后一次出现之前的所有内容,请使

int lastIndex = input.LastIndexOf(',');
if (lastIndex == -1)
{
    // Handle case with no commas
}
else
{
    string beforeLastIndex = input.Substring(0, lastIndex);
    ...
}
Run Code Online (Sandbox Code Playgroud)