Skip to content

58. Length of Last Word #49

Answered by mah-shamim
mah-shamim asked this question in Q&A
Jul 17, 2024 · 1 comments · 3 replies
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Trim the String: Remove any leading or trailing spaces.
  2. Split the String into Words: Use spaces as the delimiter to split the string into an array of words.
  3. Find the Last Word: Get the last element of the resulting array.
  4. Calculate the Length: Return the length of the last word.

Let's implement this solution in PHP: 58. Length of Last Word

<?php
function lengthOfLastWord($s) {
    // Trim the string to remove any leading or trailing spaces
    $trimmed = trim($s);
    
    // Split the string by spaces
    $words = explode(' ', $trimmed);
    
    // Get the last word from the array
    $lastWord = end($words);
    
    // Return the len…

Replies: 1 comment 3 replies

Comment options

mah-shamim
Aug 1, 2024
Maintainer Author

You must be logged in to vote
3 replies
@topugit
Comment options

topugit Aug 1, 2024
Collaborator

@kovatz
Comment options

kovatz Aug 1, 2024
Collaborator

@basharul-siddike
Comment options

Answer selected by topugit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
4 participants