繁体   English   中英

C# String.Split:指定空格和附加分隔符的最佳方法?

[英]C# String.Split : Best way to specify whitespace AND additional separator characters?

对于以下任何变体, 所有空白字符都被定义为拆分字符

string[] words = phrase.Split(null); 
string[] words = phrase.Split(new char[0]); 
string[] words = phrase.Split((char[])null); 
string[] words = phrase.Split(default(Char[])); 
string[] words = phrase.Split(null as char[]);

但是否还有一种方法可以定义空格和其他分隔符,如逗号 (,) 或连字符 (-),而无需对 String.Split 进行嵌套调用,也无需明确定义每个空格字符

目标是高性能,而不是简洁的代码

您可以改用Regex.Split ,它允许您在 Regex 模式上拆分:

string[] words = Regex.Split(phrase, "[\s,-]");

模式[\\s,-]将在任何空格( \\s )或逗号或连字符文字( , , - )上拆分

请务必添加对System.Text.RegularExpressions的引用

using System.Text.RegularExpressions;

正如官方文档所说:

性能注意事项

Split 方法为返回的数组对象分配内存,并为每个数组元素分配一个 String 对象。 如果您的应用程序需要最佳性能,或者如果管理内存分配对您的应用程序至关重要,请考虑使用 IndexOf 或 IndexOfAny 方法,以及可选的 Compare 方法,在字符串中定位子字符串。

如果您需要高性能,您应该使用Span<string>和方法IndexOfSlice

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM