方法一:从后遍历
int lengthOfLastWord(char * s) {
int len = strlen(s) - 1;
char *p = s;
int count = 0;
if(len == -1)
{
return 0;
}
while ((count == 0 || *(p+len) != ' ') && len > 0)
{
if (*(p+len) != ' ')
{
count++;
}
len--;
}
if (*(p + len) != ' ')
{
count++;
}
return count;
}
方法二:从前遍历
int lengthOfLastWord(char * s){
char *p = s;
char *q = s;
while(*p != '\0')
{
if(*p == ' ' && *(p+1) != ' ' && *(p+1) != '\0')
{
q = p;
q++;
}
p++;
}
int count = 0;
while(*q != '\0' && *q != ' ')
{
count++;
q++;
}
return count;
}