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?
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
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.
yourString.Substring(yourString.LastIndexOf('/') + 1);
您可以按相反的顺序运行for循环,直到/
符号为止。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.