您的位置:首页 > 其它

将字符串按固定长度分隔成子串

2013-06-23 23:19 232 查看
面试题:写一个函数,要求输入一个字符串和一个字符长度,对此字符串进行分隔。

/***
* 将字符串按固定长度切割成字符子串
* @param src 需要切割的字符串
* @param length 字符子串的长度
* @return 字符子串数组
*/
public 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
;

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;
}


测试代码如下:

//测试代码
String str = "hello world,this is my test program";
SplitString splitString = new SplitString();
String[] result = splitString.splitStringByLength(str, 6);
for (int i = 0; i < result.length; i++) {
System.out.println("subString" + i + ":" + result[i]);
}


结果打印:
now split "hello world,this is my test program" by length 6
subString0:hello
subString1:world,
subString2:this i
subString3:s my t
subString4:est pr
subString5:ogram
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐