Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = “Hello World”,
return 5.
题意:求取字符串中最后一个单词的长度,若不存在则返回0,字符串中只包括空格和单词
解题思路:
解题思路:求最后一个单词的长度,一个字符串包括单词和空格,
所以我们需要去除字符串最后的空格和字符串开始的空格,对字符串查询函数
字符串查询函数strrchr(const char *s, char ch)查询s字符串中最后一次出现ch字符的位置,并返回其位置
C语言实现代码:
/** * 解题思路:求最后一个单词的长度,一个字符串包括单词和空格, * 所以我们需要去除字符串最后的空格和字符串开始的空格,对字符串查询函数 * 字符串查询函数strrchr(const char *s, char ch)查询s字符串中最后一次出现ch字符的位置,并返回其位置 */
int lengthOfLastWord(char *s) {
int i, j;
char *str, *p;
p = NULL;
if(s == NULL) return 0;
i = 0;
while(*(s + i) != '\0'){//获取字符串的长度
i++;
}
while(*(s+i-1) == 32){//判断字符串最后面有没有空格,ASCII码32代表空格,若有空格长度减一
i--;
}
j = 0;
while(*(s+j) == 32){//判断字符串前面有没有空格,若有j+1
j++;
}
if(i <= j) return 0;//若i<=j表示字符串全由空格组成,没有单词
str = (char *)malloc((i+1)*sizeof(char));
memset(str, 0, sizeof(str));//把不包括前后空格的字符串复制给str
strncpy(str, s+j, i-j);
p = strrchr(str, 32);//从后开始
if(p == NULL){
return i-j;
}else {
return (str+i-j-1) - p;
}
}