Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to find the length of the last word in C++

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to find the length of the end word on C++". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to find the length of the end word on C++" can help you solve the problem.

Length of Last Word calculates the length of the last word

Given a string s consists of upper/lower-case alphabets and empty space characters "", return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"

Output: 5

This problem is not very difficult. First preprocess the input string, remove the spaces at the beginning and end, and then use a counter to accumulate the length of the string that is not blank. If you encounter spaces, the counter will be cleared to zero. See the code below:

Solution 1:

Class Solution {public: int lengthOfLastWord (string s) {int left = 0, right = (int) s.size ()-1, res = 0; while (s [left] = = "") + + left; while (s [right] = = "")-right; for (int I = left; I = 0 & & s [right] = ")-right While (right > = 0 & & s [right]! = ") {--right; + + res;} return res;}}; that's all for" how to find the length of the last word in C++ ". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report