String.split使用点时返回null [英] String.split returning null when using a dot
问题描述
我得到这个简单的code:
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的?
My question is why does ipArray stay null even though I'm setting it to split on each of ip's .s?
推荐答案
使用 ip.split(\\\\);
和你的问题将得到解决。问题是,的字符串#分裂收到常规恩pression,点(。)符号在正规前pressions一个特殊字符,所以你需要逃避它为它是PTED间$ p $作为一个普通的点,也因为反斜线在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屋!