我正在研究一种基于 .分隔符,我已经使用了 Pattern 和 Matcher 类,并获取了分隔符的起始位置并将它们存储在一个数组中,现在我想根据这些起始位置分割指定的字符串,我的问题是,当我尝试以下代码时,程序将永远运行(无限循环)。
public void cutByRegex(){
String outPut="";
int i=0;
int startIndex[]=new int[3];
System.out.println("IP--->"+ip);
Pattern p=Pattern.compile("\\.");
Matcher m=p.matcher(ip);
while (m.find()){
startIndex[i]=m.start();
i++;
System.out.println("start: "+m.start());
}
System.out.println("StartIndices-->");
for(int j:startIndex)
System.out.println(j);
for(i=0;i<startIndex.length+1;){
switch(i){
case 0:
outPut+=ip.substring(i,startIndex[i]);
i++;
case 1:
outPut+=ip.substring(startIndex[i]-1,startIndex[i]);
i++;
case 2:
outPut+=ip.substring(startIndex[i]-1,startIndex[i]);
outPut+=ip.substring(startIndex[i],ip.length());
break;
}
System.out.println("group--->"+outPut);
}
}
例如: startIndex 数组包含 3,5,7 我想对 127.1.1.254 进行子串 从0--->3 从4--->5 从6--->7 从8开始--->ip.length
注意:我很了解内置方法 split(),我想手动完成这项工作 我犯了什么错误??
最佳答案
您没有在 for 循环 i 变量和 case block 2 中使用增量部分
你的代码
for(i=0;i<startIndex.length+1;){
case 2:
outPut += ip.substring(startIndex[i] - 1, startIndex[i]);
outPut += ip.substring(startIndex[i], ip.length());
break;
}
change with it
for (i = 0; i < startIndex.length + 1;i++) {
case 2:
outPut += ip.substring(startIndex[i] - 1, startIndex[i]);
outPut += ip.substring(startIndex[i], ip.length());
i++;
break;
}
关于java - 根据点分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13926358/