题解 | #字符串最后一个单词的长度#

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

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

// 法一:读取一行,从后往前检查到空格后,取最后单词的长度
#include <iostream>
#include <array>
using namespace std;

int StrLen(const std::string &str)
{
	int index = 0;
	for (int i = str.size(); i >= 0; i--)
	{
		if (str[i] == ' ')
		{
			index = i + 1;
			break;
		}
	}

	int len = str.size() - index;
	return len;
}

int main()
{
	std::array<char,5000> str = { 0 };
	while (cin.getline((char*)str.data(),sizeof(str)))
	{
		cout << StrLen(str.data()) << endl;
	}
}
// 64 位输出请用 printf("%lld")

// 法二:因为scanf会在遇到空格或者结束符时停止读入,故可以将输入前面的都丢了,直到遇到结束符,那么最后一次即为最后一个单词
#include <stdio.h>
#include <string.h>

int main()
{
	char str[5000] = { 0 };
	while (scanf("%s", str) != EOF);

	int len = strlen(str);
	printf("%d\n", len);
}

#每日一题挑战#
全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务