public class TestReplace {//模拟string的replace方法,不能使用其他工具类
public static void main(String[] args) {
String string = "aacbssccbccb";
String str1 = "cb";//当前字符串
String str2 = "dd";//替换成dd字符串
String[] split = string.split(str1);
System.out.println("原字符串 = " + string);
if (string.substring(0, str1.length()).equals(str1)) {//判断字符前后是否以当前字符串结束
split[0] = str2 + split[0];
}
if (string.substring(string.length() - str1.length()).equals(str1)) {
split[split.length - 1] = split[split.length - 1] + str2;
}
for (int i = 0; i < split.length - 1; i++) {//首末位置字符串前面已做判断
split[i] = split[i] + str2;
}
String strFinal = "";
for (String s : split) {
strFinal += s;
}
System.out.println("strFinal = " + strFinal);
}
}