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