题目来源:
力扣https://leetcode.cn/problems/length-of-last-word/题目简介:
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
思路:
通过遍历检测字符串中的空格再检测第一个非空格的字符,检测非空格且不是第一个时,开始计数
代码实现:
int lengthOfLastWord(char * s)
{
int count = 0;
int i;
bool find = false;
int countbak = 0;
for(i = 0; i <strlen(s); i++)
{
if(s[i] == ' ')
{
if(find)
{
countbak = count;
}
count = 0;
find = false;
}
else if(!find)
{
find = true;
count++;
}
else if(find)
{
count++;
}
}
if(find)
{
return count;
}
return countbak;
}