[英]How can I split the last instance of a character in a C# string?
我有一个看起来像这样的字符串
/root/test/test2/tesstset-werew-1
我想在最后一个/
后面解析这个词。 因此,在此示例中,我想抓住单词tesstset-werew-1
。 用C#做到这一点的最佳方法是什么? 我应该将字符串拆分为数组还是为此提供一些内置函数?
string mystring = "/root/test/test2/tesstset-werew-1";
var mysplitstring = mystring.split("/");
string lastword = mysplitstring[mysplitstring.length - 1];
如果这是路径,在您的示例中似乎是这种情况,则可以使用Path.GetFileName()
:
string fileName = Path.GetFileName("/root/test/test2/tesstset-werew-1");
拆分为数组可能是最简单的方法。 另一个将是regex
这样的事情会工作:
string[] segments = yourString.Split('/');
try
{
lastSegment = segments[segments.length - 1];
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Your original string does not have slashes");
}
您可能想检查一下segment []在第二条语句之前是否包含元素。
yourString.Substring(yourString.LastIndexOf('/') + 1);
您可以按相反的顺序运行for循环,直到/
符号为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.