java用什么方法分割这样的字符串

例如 将1234567890
分为 12 34 56 78 90这样的五份

就是二楼说的那样。

1. substring();

public class Temp {
public static void main(String[] args) {
String str = "1234567890";
//每段的长度
int step = 2;
int length = str.length();
for (int i = 0; i < length; i += step){
//结束的位置
int end = i + step;
if (end > length){
//避免越界
end = length;
}
System.out.println(str.substring(i, end));
}
}
}

2. 正则表达式

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Test {
public static void main(String[] args){
String str = "1234567890";
Pattern regex = Pattern.compile(".."); //匹配两个字符
Matcher m = regex.matcher(str); //获取匹配对象
while(m.find()){
System.out.println(m.group()); //输出匹配的每一组内容
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-14
用循环使用substring函数。
如果是每两个数字分一下。也可以考虑使用正则表达式匹配。
方法不止一种了
第2个回答  2014-12-14
java中没有现成的方法。如果你要分成5份的话,最好自定义一个函数进行拆分。
相似回答