今天实现一个字符串拼接的一个需求,比如:
输入:
int times = 3;
String str = "abcd";
输出:
abcdabcdabcd
本身想自己用StringBuffer写的,后来稍微查了下,发现org.apache.commons.lang.StringUtils.repeat实现了,稍微看了下它的实现,感觉这个库的作者实现的比我们想象的严禁多了。
下来我们看下:
public static String repeat(String str, int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null ) { return null ; } if (repeat <= 0) { return EMPTY ; } int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return padding(repeat, str.charAt(0)); } int outputLength = inputLength * repeat; switch (inputLength) { case 1 : char ch = str.charAt(0); char [] output1 = new char[outputLength]; for (int i = repeat - 1; i >= 0; i--) { output1[i] = ch; } return new String(output1); case 2 : char ch0 = str.charAt(0); char ch1 = str.charAt(1); char [] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default : StringBuffer buf = new StringBuffer(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } }
实现的亮点我来稍微总结下
- 开头的时候就进行了参数的校验,这个里面我个人的感觉,如果repeat为0的时候,应该返回原字符串,为什么要返回empty?
- 这个里面如果是单个字符repeat的话,会判断repeat次数和PAD_LIMIT的关系,PAD_LIMIT为8192,这个我就有点不大明白
- 后面就进行了判断,如果是一个字符的话,构建char数组,这个比较好理解
- 如果是两个字符的话,这个地方少循环了一次,我感觉我写程序的话,这块考虑不到
- 最后使用StringBuffer,这点和我想到的一致
最后总结下,看这些程序确实能提高自己的认知和考虑问题的周到性。
相关推荐
org.apache.commons.lang3.StringUtils.jar,打开是common-lang3.jar文件,以及使用方法,根据使用方法使用即可,绝对可靠
StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if (index != -1) { return ip....
StringUtils 方法的操作对象是 java.lang.String 类型的对象,是 ...除了构造器,StringUtils 中一共有130多个方法,并且都是 static 的,所以我们可以这样调用 StringUtils.xxx() 下面分别对一些常用方法做简要介绍:
StringUtils函数全集StringUtils函数全集
StringUtils 字符串工具类,基本上是封装的commons.lang3.StringUtils,有需要的可以下载看下
xwork-core-2.1.6.jar这个版本才内含StringUtils.class这个工具类,我已经将这个类添加到xwork-core-2.3.34.jar内了。
StringUtils.cpp
继承了org.apache.commons.lang3.StringUtils工具类,加入了部分常用方法,使用时直接添加到项目的公共utils下,同时在pom.xml加入依赖: <!-- ...
jar包中的StringUtils类用于操作字符串的各种判断和截取
字符串工具概要包含一些用于格式化和操作字符串的基本实用程序: StringUtils.format 的工作方式类似于 .Net 中的 String.Format。代码示例 s1 = StringUtils.format("The {0} is against the {1}.", "chair", "wall...
String utilities tutorial for basic4android developers.
详细讲解SringUtils源代码中的方法使用
DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19楼蓝色风格DX2 ndsns19...
StringUtils.java StringUtils.java
包含有org.apache.commons.lang3.StringUtils; org.apache.commons.lang3.reflect.FieldUtils等类
Compare用法Compare用法Compare用法Compare用法Compare用法Compare用法
StringUtils.java 基于commons-lang-2.5.jar提取 附带使用文档StringUtils.doc
主要介绍了详解Spring的StringUtils踩坑记录,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
此帮助类是判断字符串为空,包括(null,"","null"),在写代码时有非常大的帮助,具体使用详见:https://www.jianshu.com/p/a1fa86a710c0