题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
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);
}
#每日一题挑战#
