java 如何验证 string.split() 是否返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14854937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to verify if a string.split() returns null
提问by Kalec
I am reading data from a file:
我正在从文件中读取数据:
Some Name;1|IN03PLF;IN02SDI;IN03MAP;IN02SDA;IN01ARC
Some Other Name;2|IN01ALG;IN01ANZ
Another Name;3|
Test Testson;4|IN03MAP;IN01ARC;IN01ALG
I use string.split() for every line I read from that file, like this:
我从该文件中读取的每一行都使用 string.split() ,如下所示:
String args[] = line.split("\|");
String candidatArgs[] = args[0].split(";");
if (args[1] != "" || args[1] != null) {
String inscrieriString[] = args[1].split(";");
Thing is:when I reach Another Name;3|
after .split("\\|")
the second part (args[1]
) should be empty, either null
or ""
(I don't really know).
事情是:当我到达Another Name;3|
之后.split("\\|")
的第二部分(args[1]
)应该是空的,要么null
或""
(我真的不知道)。
HoweverI get an Array index out of bounds error on if (args[1] != "" || args[1] != null)
(again, at: Another Name;3|
)
但是我得到一个数组索引上界失误if (args[1] != "" || args[1] != null)
(再次,网址为:Another Name;3|
)
回答by David Lavender
The args will only have one element in it.
args 中只有一个元素。
if (args.length > 1) { String inscrieriString[] = args[1].split(";"); }
回答by Andreas Fester
You need to check the length of your args
array.
您需要检查args
数组的长度。
String.split()
returns an array of length 1 for your third line, so that args[1]
is out of bounds.
You should also use String.isEmpty()
instead of != ""
.
String.split()
为第三行返回长度为 1 的数组,因此args[1]
超出范围。您还应该使用String.isEmpty()
代替!= ""
.
Most likely, you can even skip your additional checks - checking the array length should be sufficient:
最有可能的是,您甚至可以跳过额外的检查——检查数组长度就足够了:
if (args.length > 1) {
String inscrieriString[] = args[1].split(";");
...
}
回答by Fritz
Check the length of args
when splitting and only access the other index if the length allows it (if the args.length > 1
).
检查args
拆分时的长度,如果长度允许,则仅访问另一个索引(如果args.length > 1
)。
In this case:
在这种情况下:
String line = "Another Name;3|"; //simplified for the example
line.split("\|");
It will return this array:
它将返回这个数组:
{ "Another Name;3" }
回答by user902383
try
尝试
String args[] = line.split("\|",2);
String candidatArgs[] = args[0].split(";");
if (args.length==2)
String inscrieriString[] = args[1].split(";");
回答by fgb
args[1]
isn't empty or null. It is out of bounds in the array.
args[1]
不为空或为空。它在数组中越界。
System.out.println("Another Name;3|".split("\|").length);
You would need to check the length of the array before using it.
在使用之前,您需要检查数组的长度。
回答by Marc-Emmanuel Ramage
I think you can test the length of args and it should return 1 or 2. If it's 1 you know that there's no args[1].
我认为你可以测试 args 的长度,它应该返回 1 或 2。如果它是 1,你就知道没有 args[1]。