58. Length of Last Word
2016-03-11 11:26
441 查看
题目:
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.
For example,
Given s = “Hello World”,
return 5.
代码:
lastIndexOf指定字符串在此实例中的最后一个匹配项的从零开始的索引位置trim() 函数移除字符串两侧的空白字符或其他预定义字符
public class Solution { public int lengthOfLastWord(String s) { s = s.trim(); int lastIndex = s.lastIndexOf(' ') + 1; return s.length() - lastIndex; } }
可以合成一行:
public int lengthOfLastWord(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1; }
相关文章推荐
- 后缀名“.dll .obj .lib”和“ .so .o .a”文件的区别含义
- 第二次c++上机实验
- ecshop 后台模板设置-》设置模板
- HeadFirst设计模式之状态模式
- 第四届蓝桥杯真题
- 使用"yum"管理软件包
- iOS APP上线流程
- Java基础学习
- iOS将颜色转换image方法
- Android开发之创建自己的内容提供器并测试
- NSRunloop 个人思考与实践
- 多线程之GCD(1)
- 在MFC中,edit无法粘贴、剪切的解决方法。
- c++第1次实验-2
- Apache Arrow:一个跨平台的内存数据交换格式
- git 常用命令及问题解决(转)
- Android SnackBar使用方法
- Where is the python library installed?
- backbone学习笔记一
- 简易透明黑色背景