这个问题和我之前的问题Split a string contain dash and minus sign类似。 。但我问错了,然后它的语义略有不同,人们从这个角度回答(包括)。因此,我认为最好提出一个新问题,而不是修改该问题。
我必须拆分一个包含连字符减号字符和减号的字符串。我尝试根据 unicode 字符( https://en.wikipedia.org/wiki/Hyphen#Unicode )进行分割,但仍然考虑减号与连字符减号字符相同。有什么办法可以解决吗?
预期输出
(计数)
(美国)
-1
实际输出
(计数)
(美国)
//实际上空行会打印在这里,但 SO 编辑器挤压空行
1
public static void main(String[] args) {
char dash = '-';
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("-", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
}
最佳答案
char dash = '\u2010'; // 2010 is hyphen, 002D is hyphen-minus
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("\u2010", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
整数的字符串表示形式始终使用连字符减号作为负号:
来自Integer.toString
:
If the first argument is negative, the first element of the result is the ASCII minus character '-' ('\u002D'). If the first argument is not negative, no sign character appears in the result.
所以最后你的字符串有 3 个连字符减号。这就是为什么 split
无法区分它们。
由于您无法更改整数的字符串表示形式,因此需要更改 dash
变量以存储连字符而不是连字符减号。现在字符串中有 2 个连字符和 1 个连字符减号,使得 split
能够区分它们。
关于java - 拆分包含连字符和减号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747089/