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 calculate the length of the last word of a string in C language

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

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how the C language calculates the length of the last word of the string. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something from this article.

Description:

Calculates the length of the last word of the string, separated by spaces, and the string length is less than 5000. (note: the string does not end with a space)

Enter a description:

Enter a line that represents the string to be calculated, which is not empty and is less than 5000 in length.

Output description:

Outputs an integer that represents the length of the last word of the input string.

Example:

Input: hello nowcoder,

Output: 8

Description: the last word is nowcoder with a length of 8

Train of thought:

First, define a variable pos to find the position of the space before the last word. After finding the space, pos+1 is the first letter position of the last word.

two。 Secondly, s.size ()-(pos+1) is the length of the last word.

3. If no space is found, the first word is the last word, and the length is s.size ()

The code is as follows:

# include#includeusing namespace std;int main () {string s; getline (cin,s); / / you can enter spaces with getline (not split like cin) size_t pos=s.rfind (''); / / look for''if (positing strings) {cout

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

Development

Wechat

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

12
Report