我有一个类似 abc~def~ghij~klm~nop~qrstu~vwx~hj
的字符串。我只想将它拆分两次(结果分为三部分):这意味着无论我在哪里得到 ~
符号,我都需要拆分 abc
、def
第三个仅作为单个字符串 ghij~klm~nop~qrstu~vwx~hj
。
我知道如何在 ~
符号出现的地方拆分成字符串
String[] parts = stat.split("~");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
这里我只得到第 3 部分作为 ghij
,我需要整个字符串用 ~
符号保持长。
最佳答案
这只会将 stat
字符串拆分两次,即将其拆分为 3 部分:
String[] parts = stat.split("~", 3);
String.split(String regex, int limit)
方法允许控制结果部分的数量。
引用 Javadoc:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
关于java - 仅拆分字符串两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349245/