读书人

StringUtils源码懂得(中)有点意思的

发布时间: 2012-10-14 14:55:08 作者: rapoo

StringUtils源码理解(中)有点意思的方法

这次不按照前面的介绍了,方法都大同小异,下面就介绍几个有意思一点的方法

1.left,取左边几个字符

同理,有 right方法,有mid方法,取中间几个。实现都是用substring实现

例如:

StringUtils.left("abc", 0)   = ""StringUtils.left("abc", 2)   = "ab"StringUtils.left("abc", 4)   = "abc"

?这个可能在字符串判断中用到

 public static String left(String str, int len) {        if (str == null) {            return null;        }        if (len < 0) {            return EMPTY;        }        if (str.length() <= len) {            return str;        }        //这一句话是实现。        return str.substring(0, len);}
2.substringBefore(str,separator),找到出现separator之前的字符串。

实现就是先找到出现separator的位置,然后切字符串。

3.删除全部空格及空格类似字符

实现就是每个比对,通过的写入char[]中。

 public static String deleteWhitespace(String str) {}
4.删除某个字符串
//感觉这个方法写的很干脆public static String removeStart(String str, String remove) {        if (isEmpty(str) || isEmpty(remove)) {            return str;        }        if (str.startsWith(remove)){            return str.substring(remove.length());        }        return str;}//直接替换public static String remove(String str, String remove) {        if (isEmpty(str) || isEmpty(remove)) {            return str;        }        return replace(str, remove, EMPTY, -1);}
5.repeat 重复

例子:

StringUtils.repeat(null, 2) = nullStringUtils.repeat("", 2)   = ""StringUtils.repeat("a", 3)  = "aaa"StringUtils.repeat("ab", 2) = "abab"StringUtils.repeat("a", -2) = ""StringUtils.repeat("", "x", 3)    = "xxx"StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
?
//这个就是实现的原理, public static String repeat(char ch, int repeat) {          //创建一个重复过后的数组,然后往里写入字符        char[] buf = new char[repeat];        for (int i = repeat - 1; i >= 0; i--) {            buf[i] = ch;        }        return new String(buf);}
6.首字母大写
public static String capitalize(String str) {        int strLen;        if (str == null || (strLen = str.length()) == 0) {            return str;        }        //首字母大写,然后切割后面的        return new StringBuilder(strLen)            .append(Character.toTitleCase(str.charAt(0)))            .append(str.substring(1))            .toString();}

?另外还有首字母小写的方法uncapitalize(),还有大小写装换的swapCase()。

7.统计字符串中出现某个字符串的次数
//统计出现次数"aaaa"出现"aa"算两次public static int countMatches(CharSequence str, CharSequence sub) {        if (isEmpty(str) || isEmpty(sub)) {            return 0;        }        int count = 0;        int idx = 0;        //查看是否包含        while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {            //包含的话,位置加上匹配的长度,这样才会有"aaaa"出现"aa"两次,而不是三次。            count++;            idx += sub.length();        }        return count;}
8.判断是否是数字
public static boolean isNumeric(CharSequence cs) {        if (cs == null || cs.length() == 0) {            return false;        }        int sz = cs.length();        for (int i = 0; i < sz; i++) {            //比较每一个字符对应的数字是否在一定f范围内            if (Character.isDigit(cs.charAt(i)) == false) {                return false;            }        }        return true;}
9.将字符串颠倒
public static String reverse(String str) {        if (str == null) {            return null;        }        //这里的实现就是两个字符数组的赋值操作        return new StringBuilder(str).reverse().toString();}
10.将多余字符变成...

还有可以从中间加入的

例子

StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
?
public static String abbreviate(String str, int maxWidth) {        return abbreviate(str, 0, maxWidth);}public static String abbreviate(String str, int offset, int maxWidth) {        if (str == null) {            return null;        }        //如果最大字符小于4,就报错,因为一个。就是一个字符        if (maxWidth < 4) {            throw new IllegalArgumentException("Minimum abbreviation width is 4");        }        if (str.length() <= maxWidth) {            return str;        }        if (offset > str.length()) {            offset = str.length();        }        if (str.length() - offset < maxWidth - 3) {            offset = str.length() - (maxWidth - 3);        }        final String abrevMarker = "...";        //替换最大字符数的最后三个字符为...        if (offset <= 4) {            return str.substring(0, maxWidth - 3) + abrevMarker;        }        //这里限制前面的字符是,前面三个+后面三个,所以不能小于7       ?if (maxWidth < 7) {            throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");        }        if (offset + maxWidth - 3 < str.length()) {            return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3);        }        return abrevMarker + str.substring(str.length() - (maxWidth - 3));}
11.列出两字符串不同的内容(列出第二个参数不同的部分)
//例如: difference("i am a machine", "i am a robot") -> "robot"public static String difference(String str1, String str2) {        if (str1 == null) {            return str2;        }        if (str2 == null) {            return str1;        }        //列出str1从开始匹配,到不一样的位置开始,然后将这个位置返回,全部一样就返回-1        int at = indexOfDifference(str1, str2);        if (at == INDEX_NOT_FOUND) {            return EMPTY;        }        return str2.substring(at);}

?同样还有去相同部分的getCommonPrefix

12.直接带编码的toString
public static String toString(byte[] bytes, String charsetName) throws UnsupportedEncodingException {        return charsetName == null ? new String(bytes) : new String(bytes, charsetName);}
13.休息

现在StringUtils就剩下两个地方没看了:

一个是Levenshtein距离

还有一个是内部类InitStripAccents

?

?

?

?

读书人网 >编程

热点推荐