lintcode: 左填充
2016-07-07 14:56
375 查看
[b]题目[/b]
实现一个leftpad库,如果不知道什么是leftpad可以看样例
样例
leftpad("foo", 5) >> " foo" leftpad("foobar", 6) >> "foobar" leftpad("1", 2, "0") >> "01"
解题 public class StringUtils { /** * @param originalStr the string we want to append to with spaces * @param size the target length of the string * @return a string */ static public String leftPad(String originalStr, int size) { // Write your code here int n = originalStr.length(); if(n>=size) return originalStr; int k = size - n; StringBuffer newStr = new StringBuffer(); while(k>=1){ newStr.append(' '); k--; } newStr.append(originalStr); return newStr.toString(); } /** * @param originalStr the string we want to append to * @param size the target length of the string * @param padChar the character to pad to the left side of the string * @return a string */ static public String leftPad(String originalStr, int size, char padChar) { // Write your code here int n = originalStr.length(); if(n>=size) return originalStr; int k = size - n; StringBuffer newStr = new StringBuffer(); while(k>=1){ newStr.append(padChar); k--; } newStr.append(originalStr); return newStr.toString(); } }
相关文章推荐
- 聊聊分布式事务
- 基于CoreText的基础排版引擎
- android developer tiny share-20160704
- android developer tiny share-20160704
- 《机器学习实战》之决策树
- Java的常见异常
- RS232、RS485、TTL电平、CMOS电平区别
- Linux 下的 Redis 安装 && 启动 && 关闭 && 卸载
- poj 2001 Shortest Prefixes 字典树
- MySQL查看相关信息
- Jmeter使用过程记录---安装(一)
- Android中ViewPager + Fragment使用ButterKnife注解时出现空指针NullPoint的情况
- asp.net core 中文乱码
- 深入浅出ES6(十四):let和const
- 获得日期中的月份
- 深入浅出ES6(十四):let和const
- Poj 2001 Shortest Prefixes
- centos安装lamp环境
- iOS开发:NSURLSession和Afnetworking的使用对比
- Android 即时音视频解决方案1——环信