用String.substring方法,不小心会有越界异常。现实现一个没抛出越界异常,越界就返回null,不过直接返回的再用其它方法,可能有Null异常。现还实现可以负index的,可能逆向的。
package com.chenlb.util;
public class StringUtil {
/**
* start与end均可负数<br/>
* start < end正向取, start > end逆向取<br/>
* 示例:str="I am chenlb"<br/>
* StringUtil.substring(str, 0, 12) -> null<br/>
* StringUtil.substring(str, 12, 12) -> null<br/>
* StringUtil.substring(str, 12, 13) -> null<br/>
* StringUtil.substring(str, 4, 4) -> ""<br/>
* StringUtil.substring(str, 0, 4) -> "I am"<br/>
* StringUtil.substring(str, -4, -1) -> "enl"<br/>
* StringUtil.substring(str, -2, 4) -> "lbI am"<br/>
* StringUtil.substring(str, 4, 0) -> "ma I"<br/>
* StringUtil.substring(str, -1, -4) -> "lne"<br/>
* StringUtil.substring(str, 1, -4) -> "Iblne"<br/>
* StringUtil.substring(str, 0, -4) -> "blne"<br/>
* StringUtil.substring(str, -4, 0) -> "enlb"<br/>
* @return 越界返回null, start==end返回空
* @author chenlb 2008-6-18 下午12:39:51
*/
public static String substring(String str, int start, int end) {
if(str == null) {
return null;
}
int len = str.length();
if(Math.abs(start) >= len) {
return null;
}
if(Math.abs(end) > len) {
return null;
}
StringBuilder sb = new StringBuilder();
if(end > start) { //正向
substring(sb, str, start, end);
} else if(end == start) {
return "";
} else { //逆向 end < start
substring(sb, str, end, start);
sb.reverse();
}
return sb.toString();
}
private static void substring(StringBuilder sb, String str, int start, int end) {
int len = str.length();
if(start < 0) {
if(end < 0) {
sb.append(str.substring(len+start, len+end));
} else {
sb.append(str.substring(len+start, len));
sb.append(str.substring(0, end));
}
} else {
sb.append(str.substring(start, end));
}
}
}
测试代码:
public void testSubstring() {
String str = "I am chenlb";
assertEquals(null, StringUtil.substring(str, 0, 12));
assertEquals(null, StringUtil.substring(str, 12, 12));
assertEquals(null, StringUtil.substring(str, 12, 13));
assertEquals("", StringUtil.substring(str, 4, 4));
assertEquals("I am", StringUtil.substring(str, 0, 4));
assertEquals("am", StringUtil.substring(str, 2, 4));
assertEquals("I am chenlb", StringUtil.substring(str, 0, 11));
assertEquals("enl", StringUtil.substring(str, -4, -1));
assertEquals("lbI am", StringUtil.substring(str, -2, 4));
assertEquals("ma I", StringUtil.substring(str, 4, 0));
assertEquals("lne", StringUtil.substring(str, -1, -4));
assertEquals("Iblne", StringUtil.substring(str, 1, -4));
assertEquals("blne", StringUtil.substring(str, 0, -4));
assertEquals("enlb", StringUtil.substring(str, -4, 0));
}
posted on 2008-06-24 13:53
流浪汗 阅读(547)
评论(0) 编辑 收藏 所属分类:
JAVA/J2EE