[英]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 有一个重载,允许您指定要返回的拆分数量。 指定 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.SubString返回从指定位置开始到字符串末尾的字符串。
String.IndexOf返回字符串中指定字符的第一个索引。
要么使用string.Split
的不同重载,它允许您指定最大项目数:
var newString = myString.Split('%', 2)[1];
请注意,如果您使用 .NET Framework,则需要使用不同的重载:
var newString = three.Split(new[] { '%'}, 2)[1];
var newString = myString.Substring(myString.IndexOf('%') + 1);
我改进了@Preciousbetine 给出的代码片段
var partofstring = two.IndexOf('%') < 0 ? string.Empty : two.Substring(two.IndexOf('%') + 1);
这将检查字符串是否不包含键 %。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.