将字符串按固定长度分隔成子串
面试题:写一个函数,要求输入一个字符串和一个字符长度,对此字符串进行分隔。
1 /*** 2 * 将字符串按固定长度切割成字符子串 3 * @param src 需要切割的字符串 4 * @param length 字符子串的长度 5 * @return 字符子串数组 6 */ 7 public String[] splitStringByLength(String src, int length) { 8 //检查参数是否合法 9 if (null == src||src.equals("")) { 10 System.out.println("the string is null"); 11 return null; 12 } 13 14 if (length <= 0) { 15 System.out.println("the length < 0"); 16 return null; 17 } 18 19 System.out.println("now split \"" + src + "\" by length " + length); 20 21 int n = (src.length() + length - 1) / length; //获取整个字符串可以被切割成字符子串的个数 22 23 String[] split = new String[n]; 24 25 for (int i = 0; i < n; i++) { 26 if (i < (n -1)) { 27 split[i] = src.substring(i * length, (i + 1) * length); 28 } else { 29 split[i] = src.substring(i * length); 30 } 31 } 32 33 return split; 34 }
测试代码如下:
1 //测试代码 2 String str = "hello world,this is my test program"; 3 SplitString splitString = new SplitString(); 4 String[] result = splitString.splitStringByLength(str, 6); 5 for (int i = 0; i < result.length; i++) { 6 System.out.println("subString" + i + ":" + result[i]); 7 }
结果打印:
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