Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

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.

over 4 years ago · Santiago Trujillo Report

0

You need to re assign the variable

s=s.replaceAll(...)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!