[英]How can I split the last instance of a character in a C# string?
I have a string that looks like this 我有一个看起来像这样的字符串
/root/test/test2/tesstset-werew-1
And I want to parse the word after the last /
. 我想在最后一个/
后面解析这个词。 So in this example, I want to grab the word tesstset-werew-1
. 因此,在此示例中,我想抓住单词tesstset-werew-1
。 What is the best way of doing this in C#? 用C#做到这一点的最佳方法是什么? Should I split the string into an array or is there some built in function for this? 我应该将字符串拆分为数组还是为此提供一些内置函数?
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");
Splitting into an array is probably the easiest way to do it. 拆分为数组可能是最简单的方法。 The other would be regex
另一个将是regex
something like this would work: 这样的事情会工作:
string[] segments = yourString.Split('/');
try
{
lastSegment = segments[segments.length - 1];
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("Your original string does not have slashes");
}
You would want to put a check that segments[] has elements before the second statement. 您可能想检查一下segment []在第二条语句之前是否包含元素。
yourString.Substring(yourString.LastIndexOf('/') + 1);
您可以按相反的顺序运行for循环,直到/
符号为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.