在我的代码中,我试图操纵一个字符串:
Some text - 04.09.1996 - 40-18
Run Code Online (Sandbox Code Playgroud)
我想这分为三个子:Some text,04.09.1996,和40-18.
当我使用Split方法以连字符作为分隔符,返回值是四个字符串的数组:Some text,04.09.1996, 40,和18.如何使此代码如上所述工作?
谢谢.
Wik*_*żew 29
你应该用空格分开-:
.Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)
var res = "Some text - 04.09.1996 - 40-18".Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in res)
Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)
结果:
Some text
04.09.1996
40-18
Run Code Online (Sandbox Code Playgroud)
Dav*_*idG 16
使用字符串拆分的这个重载只能获得3个部分:
var s = "Some text - 04.09.1996 - 40-18";
var parts = s.Split(new[] { '-' }, 3);
Run Code Online (Sandbox Code Playgroud)
我假设你也想修剪空间:
var parts = s.Split(new[] { '-' }, 3)
.Select(p => p.Trim());
Run Code Online (Sandbox Code Playgroud)