问题描述: 除去字符串中出现的连续k的0,例如k=3; A000B00—>AB00 代码如下:
import java.util.Scanner;
public class RemoveZeros {
public static String solve(String string,int k){
int count=0;
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i <string.length() ; i++) {
if (string.charAt(i)=='0'){
count++;
}else {
stringBuilder.append(string.charAt(i));
if (count%k>0){
for (int j = 0; j <count%k ; j++) {
stringBuilder.append('0');
}
}
count=0;
}
}
if (count%k>0){
for (int j = 0; j <count%k ; j++) {
stringBuilder.append('0');
}
}
return stringBuilder.toString();
}
public static String solve1(String string,int k){
String regex="0{"+k+"}";
return string.replaceAll(regex,"");
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String string=scanner.nextLine();
int k=scanner.nextInt();
System.out.println(solve(string,k));
System.out.println(solve1(string,k));
}
}
运行结果如下:
|