字符串最后一位长度

题目描述

计算字符串最后一个单词的长度,单词以空格隔开。 

输入描述:

一行字符串,非空,长度小于5000。

输出描述:

整数N,最后一个单词的长度。

示例1

输入

复制
hello world

输出

复制
5
解题思路:我直接就想到用c++字符串类型的find_last_of()成员函数,找到最后一个空格所在的序号再利用字符串的长度函数做相应的运算就ok了
注意:当字符串没有空格时是特殊情况
#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>
#include <string>
#include <string.h>
#include <cstdio>
/*@author:浅滩
*family:
*time:
*/
//我好像是一个在海边玩耍的孩子,
//不时为拾到比通常更光滑的石子或更美丽的贝壳而欢欣鼓舞,
//而展现在我面前的是完全未探明的真理之海
using namespace std;

int main()
{
    string str;
    int i;
    getline(cin,str);
    i=str.find_last_of(' ');
    if(i==-1) cout<<str.size()<<endl;
    //cout<<str.size()<<endl;
    else
    cout<<str.size()-(i+1);

    //cout << "Hello world!" << endl;
    return 0;
}

转载于:https://www.cnblogs.com/cstdio1/p/11018097.html

猜你喜欢

转载自blog.csdn.net/weixin_34237596/article/details/93162743