将字符串按固定长度分隔成子串
2013-06-23 23:19
232 查看
面试题:写一个函数,要求输入一个字符串和一个字符长度,对此字符串进行分隔。
测试代码如下:
结果打印:
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
/*** * 将字符串按固定长度切割成字符子串 * @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
相关文章推荐
- hive sql按照固定长度分隔字符串
- 【CROC 2016 - Elimination RoundE】【DP】Intellectual Inquiry 长度为m字符串后添加n位最大本质不同子串个数
- 求一字符串最长不重复字符子串的长度【Java 版】
- 求字符串中最长连续数字子串的长度
- 求字符串中不含重复字符的最长子串的长度
- 找出字符串中最大子串的长度(要求子串中的字符不重复)
- 输入一个字符串,要求找出字符串中最大子串的长度
- 实现gridview中checkbox的全选和反选,以及固定gridview列字符串的长度,多余的以...表示
- JavaScript 字符串数字左补位,右补位,取固定长度,截位扩展函数代码
- 求两个字符串的前后重叠的最长子串的长度
- 百度面试题 求字符串中不含重复字符的最长子串长度
- 输入整数(n是小于9位数的整数),当作字符串处理, 看是否有相同的子串,如1212,相同子串是12, 141516则没有子串(子串长度必须大于等于2)。 若
- C语言 求一个字符串中最长回文子串的长度
- 【算法题】查找字符串中无重复最长子串的长度
- C++_USACO_求一个字符串的从开头字母开始,直到发现某一不相同字母时,这个子串的长度
- zoj Rescue the Rabbit AC自动机+状态压缩DP n个有价值的子串,求长度为len的字符串的最大值(每子串的值最多用一次)
- 实现gridview 固定gridview列字符串的长度,多余的以...表示
- 华为上机题:求N个字符串的最长公共子串,字符串长度不超过255。
- python实现对指定字符串补足固定长度倍数分组输出
- 长度小于8000(varchar类型),以"逗号"分隔的字符串