题目

实现一个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();
}
}

最新文章

  1. sql单表中某一字段重复,取最近3条或几条数据
  2. win2003 64位系统IIS6.0 32位与64位间切换
  3. iOS 容器 addChildViewController
  4. jQuery中each()、find()、filter()等节点操作方法
  5. 基于LDA对关注的微博用户进行聚类
  6. Halcon学习笔记之缺陷检测(二)
  7. android-----JNI学习 helloworld
  8. C# 的sql server like 的参数
  9. 【开发技术】refactor 重构----实现文件改名
  10. tomcat启动命令行中文乱码
  11. 浅谈Tarjan算法
  12. nodejs+express+socket.io
  13. C++ STL next_permutation(快速排列组合)
  14. [转]awsome-python
  15. ubuntu安装gitlab-ci-runner、注册
  16. 怎么简单高效破解MyEclipse10、获取注册码
  17. ueditor+word粘贴上传
  18. buffers与cached
  19. OpenGL学习--01--打开一个窗口
  20. MYSQL 数据库结构优化

热门文章

  1. UITableView表视图以及重建机制
  2. 条款24:若所有的函数参数可能都需要发生类型转换才能使用,请采用non-member函数
  3. [LAMP]【转载】——PHP7.0的安装
  4. Android -- TouchEvent的分发和截获方式
  5. Android -- 分享功能和打开指定程序
  6. 【每日scrum】NO.5
  7. Python科学计算(一)环境简介——Anaconda Python
  8. PHP图形图像处理之初识GD库
  9. SharedPreferences实现记住密码功能
  10. 博文&零散信息阅读