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. Could anybody please explain how 1 is the result? Please note that s here contains multiple spaces, not just 1 space. StackOverflow is not allowing to enter multiple spaces.
split()
of String
returns new String[]{this}
if no match is found. In your case, s.trim()
returns ""
and s.trim().split(" ")
returns new String[]{""}
. new String[]{""}
is an array with 1 length. If you execute the expression System.out.println(s.trim().split(" ")[0].equals(""))
you will get true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.