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

1
  • We wouldn't know what you should have. What you did get is precisely the result I would expect though, given your test input and the code. Commented Apr 29, 2017 at 10:58

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You need to re assign the variable

s=s.replaceAll(...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.