使用点时 String.split 返回 null [英] String.split returning null when using a dot
问题描述
我得到了这个简单的代码:
I got this simple code:
String ip = "1.2.3.4";
String[] ipArray = ip.split(".");
System.out.println(ipArray[1]);
并且 ipArray
在它遇到 System.out.println
时为空(抛出空指针异常).
And ipArray
is null by the time it hits System.out.println
(throws null pointer exception).
我的问题是为什么即使我将 ipArray 设置为在每个 ip 的 .s 上拆分,为什么 ipArray 仍为空?
My question is why does ipArray stay null even though I'm setting it to split on each of ip's .s?
推荐答案
使用ip.split("\\.");
,你的问题就会迎刃而解.问题是 String#split 接收正则表达式,点 (.) 符号是正则表达式中的特殊字符,因此您需要对其进行转义才能将其解释为普通点,反斜杠也是转义Java中的字符,你也必须转义它.
Use ip.split("\\.");
and your problems will be solved. The problem is that String#split receives a regular expression, the dot (.) symbol is a special character in regular expressions, so you need to escape it for it to be interpreted as a plain dot, also as the backslash is an escape character in Java, you have to escape it too.
这篇关于使用点时 String.split 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!