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
.
1.“word ”
2. " "
3. "word"
4." word "
int lengthOfLastWord(const char *s) {
int length = strlen(s);
int count = 0;
for(int i= length-1; i>=0;i--){
if(s[i] == ' '){
if(count == 0) continue;
else return count;
}
count++;
}
return count;
}
Java解法:
利用split()函数,通过空格“ ”将原字符串分组
public int lengthOfLastWord(String s) {
String [] splitStrings = s.split(" ");
for(int i=splitStrings.length-1;i>=0;i--){
if(splitStrings[i].length()>0)
return splitStrings[i].length();
}
return 0;
}
-
public String[] split(String regex)
Splits this string around matches of the given regular expression.This method works as if by invoking the two-argument
split
method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result : { "boo", "and", "foo" } o { "b", "", ":and:f" } -
Parameters:
-
regex
- the delimiting regular expression
Returns:
- the array of strings computed by splitting this string around matches of the given regular expression Throws:
-
PatternSyntaxException
- if the regular expression's syntax is invalid
-