C# 使用多个分隔符拆分字符串

C# split string with multiple separators

字符串:

string one = @"first%second";
string two = @"first%second%third";
string three = @"first%second%third%fourth";

我需要能够分隔第一个“%”分隔符之后的所有内容。 我通常会使用拆分功能:

string partofstring = one.Split('%').Last();

string partofstring = one.Split('%').[1];

但是我需要能够得到:

string oneresult = @"second";
string tworesult = @"second%third";
string threresult = @"second%third%fourth";

string.Split has an overload 允许您指定要返回的拆分数。将 2 指定为拆分数,您将得到一个数组,其中索引 0 处的元素可以丢弃,而索引 1 处的元素恰好是请求的输出

string three = @"first%second%third%fourth";
var result = three.Split(new char[] {'%'}, 2);
Console.WriteLine(result[1]); // ==> second%third%fourth

试试这个

string partofstring = one.SubString(one.IndexOf('%'));

String.SubStringreturns从指定位置开始到字符串结尾的字符串。

String.IndexOf returns 字符串中指定字符的第一个索引。

使用不同的 string.Split 重载,允许您指定最大项目数:

var newString = myString.Split('%', 2)[1];

请注意,如果您使用的是 .NET Framework,则需要使用不同的重载:

var newString = three.Split(new[] { '%'}, 2)[1];

或者,使用IndexOf and Substring自己计算:

var newString = myString.Substring(myString.IndexOf('%') + 1);

我改进了@Preciousbetine 给出的代码片段

var partofstring = two.IndexOf('%') < 0 ? string.Empty : two.Substring(two.IndexOf('%') + 1);

这将检查字符串是否不包含键 %。