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
. What is the best way of doing this in C#? Should I split the string into an array or is there some built in function for this?
我想在最后一个/之后解析这个词。所以在这个例子中,我想抓住tesstset-werew-1这个词。在C#中执行此操作的最佳方法是什么?我应该将字符串拆分成数组还是有一些内置函数?
5 个解决方案
#1
3
Split()方法
string mystring = "/root/test/test2/tesstset-werew-1";
var mysplitstring = mystring.split("/");
string lastword = mysplitstring[mysplitstring.length - 1];
#2
3
If this is a path, which seems to be the case in your example you can use Path.GetFileName()
:
如果这是一个路径,在您的示例中似乎就是这种情况,您可以使用Path.GetFileName():
string fileName = Path.GetFileName("/root/test/test2/tesstset-werew-1");
#3
1
Splitting into an array is probably the easiest way to do it. The other would be 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.
您可能需要在第二个语句之前检查segments []是否包含元素。
#4
1
yourString.Substring(yourString.LastIndexOf('/') + 1);
#5
0
You can run the for loop in reverse order till the /
sign.
您可以以相反的顺序运行for循环,直到/符号。
#1
3
Split()方法
string mystring = "/root/test/test2/tesstset-werew-1";
var mysplitstring = mystring.split("/");
string lastword = mysplitstring[mysplitstring.length - 1];
#2
3
If this is a path, which seems to be the case in your example you can use Path.GetFileName()
:
如果这是一个路径,在您的示例中似乎就是这种情况,您可以使用Path.GetFileName():
string fileName = Path.GetFileName("/root/test/test2/tesstset-werew-1");
#3
1
Splitting into an array is probably the easiest way to do it. The other would be 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.
您可能需要在第二个语句之前检查segments []是否包含元素。
#4
1
yourString.Substring(yourString.LastIndexOf('/') + 1);
#5
0
You can run the for loop in reverse order till the /
sign.
您可以以相反的顺序运行for循环,直到/符号。