Skip to main content

Command Palette

Search for a command to run...

lengthOfLastWord C++ Code

Published
•1 min read•View as Markdown
lengthOfLastWord C++ Code

This line declares the function lengthOfLastWord that takes a string s as input and returns an integer.

This line initializes a variable len to 0, which will be used to keep track of the length of the last word.

This line initializes a variable i to the index of the last character in the string s.

This line starts a while loop that checks if i is greater than or equal to 0 and if the character at index i of the string s is a space. If both conditions are true, the loop decrements i by 1 until it finds a non-space character.

This line starts another while loop that checks if i is greater than or equal to 0 and if the character at index i of the string s is not a space. If both conditions are true, the loop increments len by 1 and decrements i by 1 until it reaches the beginning of the last word.

This line returns the value of len, which is the length of the last word in the string.

More from this blog

Bandari's blog

12 posts