import java.util.Arrays;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入原字符串:");
String scrStr = scanner.nextLine();
System.out.println("请输入要删除的字符串:");
String delStr = scanner.nextLine();
Str(scrStr, delStr);
Str2(scrStr, delStr);
Str3(scrStr,delStr);
Str4(scrStr, delStr);
}
public static void Str(String scrStr ,String delStr){
int count = 0;
int index = 0;
String teString = scrStr;
while((index = scrStr.indexOf(delStr))!=-1){
count++;
scrStr =scrStr.substring(index+delStr.length()); ;
}
String s2 = delStr.substring(2);
String [] aStrings = teString.split(delStr);
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < aStrings.length; i++) {
sBuilder.append(aStrings[i]);
}
String string = new String(sBuilder);
String str1 = "";
if (string.contains(delStr.substring(2))){
String str = string.replace(delStr.substring(2), "");
str1 = str.replace(delStr.substring(0,2), "");
count++;
}
if (string.contains(delStr.substring(0,1))){
String str2 = str1.replace(delStr.substring(0,1), "");
System.out.println("源字符串中总共包含:"+count+" 个");
System.out.println("删除"+delStr+"后的字符串为");
System.out.println(str2);
}
}
public static void Str2(String scrStr ,String delStr) {
StringBuilder stringBuilder = new StringBuilder(scrStr);
int count =0;
for (int i = 0; i < stringBuilder.length(); i++) {
if (stringBuilder.indexOf(delStr,i)==i) {
count++;
stringBuilder.delete(i,i+delStr.length());
i-=delStr.length();
}
}
String rString = stringBuilder.toString();
System.out.println("源字符中总共有"+count+"个"+delStr);
System.out.println("删除后的字符为:"+rString);
}
public static void Str3(String scrStr ,String delStr){
int count=0;//计数器
String newS;//声明一个新字符串
while(true) {
newS=scrStr.replace(delStr,"");//替换所有delstr为空 生成新字符串放进新字符串 里。
int n=(scrStr.length()-newS.length())/delStr.length();//用源字符串 减去新字符串 算出delstr被减的个数,在除以delst的长度 就等于减的次数
count+=n;//依次累加次数。
scrStr=newS;//在吧新字符串赋值进源数组。
if(!newS.contains(delStr)) {
break;
}
}
System.out.println("源字符串中总共包含:"+count+"个 "+delStr+" 删除"+delStr+"后的字符串为:" +newS);
}
public static void Str4(String scrStr ,String delStr) {
int count =0;
while(scrStr.contains(delStr)){
scrStr=scrStr.replaceFirst(delStr, "");
count++;
}
System.out.println("源字符串中总共包含:"+count+"个 "+delStr+" 删除"+delStr+"后的字符串为:" +scrStr);
}
}
|
|