C# 获取最后一个斜线后的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:10:42  来源:igfitidea点击:

Get contents after last slash

c#string-parsing

提问by john cs

I have strings that have a directory in the following format:

我的字符串具有以下格式的目录:

C://hello//world

C://你好//世界

How would i extract everything after the last / character (world)?

我将如何提取最后一个 / 字符(世界)之后的所有内容?

采纳答案by Simon Whitehead

string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"

The LastIndexOfmethod performs the same as IndexOf.. but from the end of the string.

LastIndexOf方法的执行与IndexOf..相同,但从字符串的末尾开始。

回答by Justin Pihony

I would suggest looking at the System.IOnamespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property

我建议查看System.IO命名空间,因为您可能想要使用它。还有 DirectoryInfo 和 FileInfo 也可能在这里有用。特别是DirectoryInfo 的 Name 属性

var directoryName = new DirectoryInfo(path).Name;

回答by Dustin Kingen

There is a static class for working with Paths called Path.

有一个用于处理路径的静态类,称为Path.

You can get the full Filename with Path.GetFileName.

您可以使用Path.GetFileName.

or

或者

You can get the Filename without Extension with Path.GetFileNameWithoutExtension.

您可以使用Path.GetFileNameWithoutExtension.

回答by Matthew Steven Monkan

using System.Linq;

using System.Linq;

var s = "C://hello//world";
var last = s.Split('/').Last();

回答by Mohammad Rahman

Try this:

尝试这个:

string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);