[英]How to extract some part of a string?
I have a string = "C:\\Users\\Desktop\\bin\\data\\so on" 我有一个字符串=“ C:\\ Users \\ Desktop \\ bin \\ data \\ so on”
I want to extract just the "C:\\Users\\Desktop\\" part.. what is the easiest way to get the result ? 我只想提取“ C:\\ Users \\ Desktop \\”部分。.什么是最简单的获取结果的方法?
string s = @"C:\Users\Desktop\bin\data\so on";
string result = String.Join("\\",s.Split('\\').Take(3));
Result C:\\Users\\Desktop 结果 C:\\ Users \\ Desktop
Take in to account that there're two possible directory separators (your input looks like a path): 考虑到存在两种可能的目录分隔符 (您的输入看起来像一个路径):
String s = "C:\Users\Desktop\bin\data\so on";
String result = String.Join(Path.DirectorySeparatorChar.ToString(),
s.Split(Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar).Take(3));
Or if you want to keep on until "/bin"
or "\\bin"
is found you should change Take
to TakeWhile
: 或者,如果要继续操作直到找到
"/bin"
或"\\bin"
,则应将Take
更改为TakeWhile
:
String result = String.Join(Path.DirectorySeparatorChar.ToString(),
s.Split(Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar).TakeWhile(
x => !String.Equals(x, "bin", StringComparison.OrdinalIgnoreCase)));
Naive soultion as Substring(@"\\bin")
can be dangerous on inputs like that "C:\\Windows\\MyBins\\Bin\\SomeStaff"
对于诸如
"C:\\Windows\\MyBins\\Bin\\SomeStaff"
这样的输入,将天真灵魂作为Substring(@"\\bin")
可能很危险 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.