C#中的手动字符串拆分

jas*_*son 19 c# string split

在我的代码中,我试图操纵一个字符串:

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)

C#demo

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)

  • @Rawling:如果你需要空值,也可以使用`StringSplitOptions.None`.从当前任务来看,`StringSplitOptions.RemoveEmptyEntries`应该没问题.如果你想知道是否只有一个参数的`string.Split`重载,[不,所有允许字符串的重载都需要`StringSplitOptions`参数](https://msdn.microsoft.com/en-us/library /system.string.split(v=vs.110).aspx). (5认同)

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)