字符串最后一个单词的长度

题目描述

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

输入描述:

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

输出描述:

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

示例1

输入

hello world

输出

5

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {

    string input;
    getline(cin, input);
    auto it = find(input.rbegin(), input.rend(), ' ');
    if (it == input.rend()) {
        cout << input.size();
        return 0;
    }
    cout << input.size()-distance(it,input.rend());
    return 0;
}

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {

    string input;
    getline(cin, input);
    auto index=input.rfind(' ');
    if (index == string::npos) {
        cout << input.size();
        return 0;
    }
    cout << input.size() - index - 1;
    return 0;
}

#include <stdio.h>
#include <string.h>

int main() {

	char input[5001] = { 0 };
	gets(input);

	int size=strlen(input);
	for (int i = size - 1; i >= 0; i--) {
		if (input[i] == ' ') {
			printf("%d", size - i - 1);
			return 0;
		}
	}
	printf("%d", size);
	return 0;
}
This entry was posted in hwleetcode. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.