测试代码:
public class Test {
public static void main(String[] args) {
String data = "de0c0c294e31";
String[] strings = splitStringByLength(data, 4);
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
public static String[] splitStringByLength(String src, int length) {
//检查参数是否合法
if (null == src || src.equals("")) {
System.out.println("the string is null");
return null;
}
if (length <= 0) {
System.out.println("the length < 0");
return null;
}
System.out.println("now split \"" + src + "\" by length " + length);
int n = (src.length() + length - 1) / length; //获取整个字符串可以被切割成字符子串的个数
String[] split = new String[n];
for (int i = 0; i < n; i++) {
if (i < (n - 1)) {
split[i] = src.substring(i * length, (i + 1) * length);
} else {
split[i] = src.substring(i * length);
}
}
return split;
}
}
测试结果:
de0c
0c29
4e31