编程:删除字符串A中包含的字符串B
2019-07-18 本文已影响0人
御都
题目:写一段程序实现,从字符串A中删除字符串B,比如从“abcefomadm"中删除”ab",并对代码进行测试
代码如下
package re_20190101;
public class TestStr {
public static String cutStr(String stra,String strb){
String result = "";
int lengtha = stra.length();
int lengthb = strb.length();
if(lengtha < lengthb){
return stra+"的长度小于"+strb+"异常!!";
}
if(lengtha == lengthb){
if(stra.equals(strb)){
return result;
}else{
return stra;
}
}
for(int i=0;i<=(lengtha-lengthb);){
//从左到右切取strb长度的字符串temp
String temp = stra.substring(i, i+lengthb);
if(temp.equals(strb)){
//如果stra最后几个字符恰好为strb,直接返回结果
if(i==lengtha-lengthb){
return result;
}
//temp等于strb,不往result中添加什么,i往后移动strb长度
i += lengthb;
}else{
//temp不等于strb,则往result中添加初始位置的字符,i往后移动一位
result += stra.substring(i, i+1);
i++;
}
}
//如果stra最后几个字符不等于strb,则需要加上stra最后小于strb长度的这部分,作为最终返回结果
return result+stra.substring(lengtha-lengthb+1);
}
public static void main(String[] args){
String s1 = "abceefobjiemicjoeffslefmo";
String s2 = "mo";
String s3 = "jieoiojdfjllllllllllllllllllllll";
String s4 = "ef";
System.out.println("字符串A的末尾等于字符串B:"+cutStr(s1,s2));
System.out.println("字符串A长度小于字符串B:"+cutStr(s1,s3));
System.out.println("字符串B在字符串A中重复出现:"+cutStr(s1,s4));
}
}
运行结果:
字符串A的末尾等于字符串B:abceefobjiemicjoeffslef
字符串A长度小于字符串B:abceefobjiemicjoeffslefmo的长度小于jieoiojdfjllllllllllllllllllllll异常!!
字符串B在字符串A中重复出现:abceobjiemicjofslmo