Marodian
Marodian

Reputation: 539

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.

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 ""?

Upvotes: 0

Views: 1845

Answers (3)

Vikrant
Vikrant

Reputation: 178

You need to re assign the variable

s=s.replaceAll(...)

Upvotes: 0

Manish Kumar Sharma
Manish Kumar Sharma

Reputation: 13432

Java Strings are immutable so you have to store the reference to the returned String after replacement because a new String has been returned. You have written,

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

But write, s = s.replaceAll("\\s", ""); instead of above.

Wherever you perform operations on String, keep the new reference moving further.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

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.

Recall that one-argument split is the same as two-argument split with zero passed for the second parameter:

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. This string is considered trailing by split, so it is removed from the result.

This result is not going to change even if you fix the call to replaceAll the way that other answers suggest.

Upvotes: 0

Related Questions