简体   繁体   English

Java字符串拆分返回长度0

[英]Java String split returns length 0

public int lengthOfLastWord(String s) {
        s.replaceAll("\\s", "");
        String[] splittedS = s.split("\\s+");
        if(splittedS.length == 1 && splittedS[0].equals("")) return 0;
        return splittedS[splittedS.length - 1].length();
    }

I tested it out with the string " " , and it returns that the length of splittedS is 0. 我使用字符串" "对其进行了测试,并返回splittedS的长度为0。

When I trimmed the String did I get " " -> "" , so when I split this, I should have an array of length with with the first element being "" ? 当我修剪String时,是否得到了" " -> "" ,所以当我分割它时,我应该有一个长度为数组的数组,第一个元素为""

Java Strings are immutable so you have to store the reference to the returned String after replacement because a new String has been returned. Java字符串是不可变的,因此替换后必须存储对返回的字符串的引用,因为已经返回了新的字符串。 You have written, 你写,

s.replaceAll("\\s", "");

But write, s = s.replaceAll("\\\\s", ""); 但是写, s = s.replaceAll("\\\\s", ""); instead of above. 而不是上面。

Wherever you perform operations on String, keep the new reference moving further. 无论您在String上执行什么操作,都应使新引用进一步移动。

The call to replaceAll has no effect, but since you split on \\\\s+ , split method works exactly the same: you end up with an empty array. replaceAll的调用没有任何效果,但是由于您在\\\\s+ splitsplit方法的工作原理完全相同:您最终得到一个空数组。

Recall that one-argument split is the same as two-argument split with zero passed for the second parameter: 回想一下,一参数split与二参数拆分相同,第二个参数传递了零:

String[] splittedS = s.split("\\s+", 0);
//                                  ^^^

This means that regex pattern is applied until there's no more changes, and then trailing empty strings are removed from the array. 这意味着将应用正则表达式模式,直到没有更多更改为止,然后从数组中删除结尾的空字符串。

This last point is what makes your array empty: the application of \\\\s+ pattern produces an array [ "" ] , with a single empty string. 最后一点是使您的数组为空的原因: \\\\s+模式的应用程序会生成一个具有单个空字符串的数组[ "" ] This string is considered trailing by split , so it is removed from the result. 该字符串被视为通过split 尾随 ,因此将其从结果中删除。

This result is not going to change even if you fix the call to replaceAll the way that other answers suggest. 即使您按照其他答案建议的方式修复了对replaceAll的调用,此结果也不会改变。

您需要重新分配变量

s=s.replaceAll(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM