Get the App
SLTechnology News&Howtos  ›  Development  › 

How to calculate the length of the last word of a string in C language

Shulou Source: shulou.com Published: 2022-06-02 05:05:41 10月20日 Update

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

Tags: Words length characters strings spaces input content output language position line no code representative variable multiple letters that is ideas integers Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Docker Apple OPPO Reno Shulou Information