2016-12-07 206 views
2

的第二部分,我会一直像这样的字符串:提取字符串

"/FirstWord/ImportantWord/ThirdWord" 

我怎样才能提取ImportantWord?话最多只能包含一个空间,他们被forward slash分离像我把上面,例如:

"/Folder/Second Folder/Content" 
"/Main folder/Important/Other Content" 

我总是希望得到第二个字(Second FolderImportant考虑到上面的例子)

+2

使用[String.Split()](https://msdn.microsoft.com/en-us/library/system.string.split(V =创建一个由'/'字符分割的数组数组 –

回答

3

怎么样这个:

string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word 
+2

这将返回''FirstWord“'不''ImportantWord”',因为数组中的第一项是一个empy字符串(' RemoveEmptyEntries'选项是必需的) –

+0

已更新。谢谢。 – JerryGoyal

1

有几种方法可以解决这个问题。最简单的一种是采用String.split

Char delimiter = '/'; 
String[] substrings = value.Split(delimiter); 
String secondWord = substrings[1]; 

(您可能需要做一些输入检查,以确保输入的是正确的格式,否则你会得到一些例外)

另一种方法是使用regex时该模式是简单/

如果您确信这是一个路径,你可以使用其他的答案在这里提到

2

我希望你不需要使用String.Split选项eith呃与特定的字符或一些正则表达式。由于输入是指向目录的合格路径,因此可以使用System.IO.Directory类的Directory.GetParent方法,它将为父目录提供DirectoryInfo。从那里你可以把目录的名称,这将是必需的文本。如果你需要在另一个层面上获得名字的方法Directory.GetParent可以嵌套:

你可以使用这样的:

string pathFirst = "/Folder/Second Folder/Content"; 
string pathSecond = "/Main folder/Important/Other Content"; 

string reqWord1 = Directory.GetParent(pathFirst).Name; // will give you Second Folder 
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important 

附加说明。

2

你也可以试试这个:

var stringValue = "/FirstWord/ImportantWord/ThirdWord"; 
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord