题目描述
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",
return5.
思路:
- 转成字节数组,截掉右边空格
解:
package main
import (
"fmt"
"strings"
)
func lengthOfLastWord(s string) int {
if len(s) == 0 {
return 0
}
s = strings.TrimRight(s," ")
sByte := []byte(s)
res := 0
i := len(sByte)-1
for ;i>=0 ;i-- {
if sByte[i] == ' ' {
break
}
res++
}
return res
}
func main() {
s := " "
res := lengthOfLastWord(s)
fmt.Print(res)
}
网友评论