String.split() 方法 - 返回的字符串数组中标记的顺序

String.split() method - order of token in the returned String array

我正在开发一个必须处理自定义变量的应用程序 aVar-

String aVar = price/barcode/area1/true  // varName/varType/varScope/tracable

可能有一些其他属性添加到 aVar 中,由 ('/') 分隔。 要获得 varName, varType, varScope 等,我必须执行以下操作,请参阅下面的代码 -

      String[] token = aVar.split("/");  

      String varName = token[0];
      String varType = token[1];
      String varScope = token[2];
      String traceable = token[3];

这里你可以看到varName取自token[0]也就是pricevarType取自token[1]也就是'barcode' ] 等等。在这里我假设 - 拆分后 varName 总是在 token[0] 中,varType 总是在 token[1] 中等等。 现在我的问题是 - split() 方法返回的 String 数组是否总是按照它们出现的顺序包含 String 标记(价格-->条形码-->区域 1 --> 真)?

我已经用一些输入进行了几次测试,发现顺序保持不变。但我不确定 ALWAYS 是否为 VERY LONG 字符串。

Does the String array returned by the split() method always contain the String token in a order by which they are appeared (price-->barcode-->area1-->true)?

一句话-是的。 String.split保持输入字符串的顺序。

根据 javadoc 此处:

The substrings in the array are in the order in which they occur in this string.

注意 link 中的行 The substrings in the array are in the order in which they occur in this string.

如您在 javadoc 中所见,结果有一个顺序:

The substrings in the array are in the order in which they occur in this string

假设您实际调用的是 String.split(String),该方法的文档包括:

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

该方法的文档包括:

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

(强调我的。)

所以是的,它们会按顺序退回,保证。