c# - 传递多个多字符分隔符时,String.Split 方法如何确定分隔符优先级?

标签 c# string tokenize stringtokenizer

如果您有此代码:

"......".Split(new String[]{"...", ".."}, StringSplitOptions.None);

生成的数组元素是:

 1. ""
 2. ""
 3. ""

现在如果你颠倒分隔符的顺序,

"......".Split(new String[]{"..", "..."}, StringSplitOptions.None);

生成的数组元素是:

 1. ""
 2. ""
 3. ""
 4. ""

从这 2 个示例中,我倾向于得出这样的结论:Split 方法在从左到右遍历数组的每个元素时递归标记化。

但是,一旦我们将包含字母数字字符的分隔符放入等式中,显然上述理论是错误的。

  "5.x.7".Split(new String[]{".x", "x."}, StringSplitOptions.None)

结果:1。 "5"2. ".7"

   "5.x.7".Split(new String[]{"x.", ".x"}, StringSplitOptions.None)

结果:1。 "5"2. ".7"

这次我们得到相同的输出,这意味着基于第一组示例理论化的规则不再适用。 (即:如果分隔符优先级始终根据分隔符在数组中的位置确定,那么在上一个示例中我们将获得 "5.""7" 而不是 "5" & ".7"

至于为什么我要浪费时间猜测 .NET 标准 API 的工作原理,这是因为我想为我的 Java 应用程序实现类似的功能,但 StringTokenizer 和 org.apache.commons.lang.StringUtils 都没有提供这种能力使用多个多字符分隔符拆分一个字符串(即使我找到了一个提供这种能力的 API,也很难知道它是否总是使用与String.Split 方法。

最佳答案

来自 MSDN :

To avoid ambiguous results when strings in separator have characters in common, the Split operation proceeds from the beginning to the end of the value of the instance, and matches the first element in separator that is equal to a delimiter in the instance. The order in which substrings are encountered in the instance takes precedence over the order of elements in separator.

因此,对于第一种情况,“..”和“...”在同一位置被发现,它们在分隔符中的顺序用于确定使用的分隔符。对于第二种情况,在“x”之前找到“.x”。并且分隔符中的元素顺序不适用。

关于c# - 传递多个多字符分隔符时,String.Split 方法如何确定分隔符优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762440/

相关文章:

c# - 在命令提示符下运行的命令在 C# 中不起作用

c++ - 为什么字符串作为指针或字符串作为原始数组总是在重载函数中作为指针调用?

c++ append 到字符串

ruby-on-rails - 用于生成唯一链接的 Rails 插件?

jquery - 如何在 ASPTokenInput 上预填充一些标签

c# - 设置 .Top 属性,移除 Anchor 属性

c# - 如何使用正确的参数测试方法的调用?

C#:从字典中删除重复值?

java - 如何在从另一个类构建的类中搜索单词?

javascript - 如何将字符串拆分为单词和数字?