[英]string.trim() in java for string containing a lot of white spaces - its length is returned as 1 instead of 0
The following code does not work as expected:以下代码无法按预期工作:
public int countSegments(String s) {
System.out.println(Arrays.toString(s.trim().split(" ")));
return (s.trim().split(" ")).length;
}
If s = " ", then ideally it should return 0. But it returns 1 even though the array printed is empty.如果 s = " ",那么理想情况下它应该返回 0。但即使打印的数组为空,它也会返回 1。 Could anybody please explain how 1 is the result?
有人可以解释一下 1 的结果如何吗? Please note that s here contains multiple spaces, not just 1 space.
请注意,这里的 s 包含多个空格,而不仅仅是 1 个空格。 StackOverflow is not allowing to enter multiple spaces.
StackOverflow 不允许输入多个空格。
split()
of String
returns new String[]{this}
if no match is found.如果未找到匹配项,则
String
的split()
将返回new String[]{this}
。 In your case, s.trim()
returns ""
and s.trim().split(" ")
returns new String[]{""}
.在您的情况下,
s.trim()
返回""
并且s.trim().split(" ")
返回new String[]{""}
。 new String[]{""}
is an array with 1 length. new String[]{""}
是一个长度为 1 的数组。 If you execute the expression System.out.println(s.trim().split(" ")[0].equals(""))
you will get true
如果你执行表达式
System.out.println(s.trim().split(" ")[0].equals(""))
你会得到true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.