char *lengthOfLastWord(const char* s)
{
char* p = (char*)calloc(strlen(s) + 1, sizeof(char));
assert(s != NULL);
if (s == NULL)
return NULL;
int count = 0;//计数器
int max = 0;//记录最大的单词位数
int cur = 0;//字符串拷贝的下标
int i = 0;
for (; i < (int)strlen(s); i++)
{
if (isalpha(s[i]))
{
count++;//如果是单词就计数器加加
}
else
{
if (max < count)
{
max = count;//替换最大单词
cur = i;
}
count = 0;
}
}
if (max < count)//处理尾部
{
max = count;
cur = i;
}
strncpy(p, s + (cur - max), max);
return p;
}
int main()
{
const char arr[] = "abas dsaddsa";
char* p = lengthOfLastWord(arr);
printf("%s\n", p);
free(p);
return 0;
}
08-06
7992
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-06
2516
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)