PHP Challenges: Find the length of the last word in a string
PHP Challenges - 1: Exercise-24 with Solution
Input : PHP Exercises
Write a PHP program to find the length of the last word in a string.
Explanation :
Sample Solution :
PHP Code :
<?php
// Function to calculate the length of the last word in a string
function length_of_last_word($s)
{
// Check if the string is empty or contains only whitespace characters
if (strlen(trim($s)) == 0)
{
return "Blank String";
}
// Split the string into words
$words = explode(' ', $s);
// If there are multiple words, return the length of the last word
if (sizeof($words) > 1)
return strlen(substr($s, strrpos($s, ' ') + 1));
else
return "Single word";
}
// Test cases
print_r(length_of_last_word("PHP Exercises") . "\n");
print_r(length_of_last_word("PHP") . "\n");
print_r(length_of_last_word("") . "\n");
print_r(length_of_last_word(" ") . "\n");
?>
Explanation:
Here is a brief explanation of the above PHP code:
- Function definition (length_of_last_word):
- The function "length_of_last_word()" takes a string ''$s' as input.
- It first checks if the string is empty or contains only whitespace characters. If so, it returns "Blank String".
- Inside the function:
- If the string is not empty or contains only whitespace characters, it splits the string into words using the "explode()" function.
- It checks if there are multiple words in the string. If there are, it extracts the last word using "substr()" and "strrpos()" functions, and returns its length.
- If there's only one word in the string, it returns "Single word".
- Function Call & Testing:
- The "length_of_last_word()" function is tested with different input strings, including strings with multiple words, single word, empty string, and whitespace characters.
- Finally "print_r()" function prints the length of the last word or appropriate message.
Sample Output:
9 Single word Blank String Blank String
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to find majority element in an array.
Next: Write a PHP program to find the single number which occurs odd number of times and other numbers occur even number of times.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/challenges/1/php-challenges-1-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics