实现一个字符串替换

代码:

/**
 * 实现字符串替换
 */
public class Test4 {
    public static void main(String[] args) {

        //实现字符串替换

        //1.替换第一个字符串
        StringBuffer stringBuffer = repalce(new StringBuffer("abcbcbcbc"), "bc", "bd");
        System.out.println("首次匹配替换:" + stringBuffer);

        //2.替换所有匹配的字符串
        StringBuffer stringBuffer2 = repalceAll(new StringBuffer("abcbcbcbc"), "bc", "bd");
        System.out.println("全部匹配替换:" + stringBuffer2);

    }

    public static StringBuffer repalce(StringBuffer stringBuffer, String str1, String str2) {

        //替换字符串
        int start = stringBuffer.indexOf(str1);

        int len = str1.length();

        int end = start + len - 1;

        //匹配是否一样,比较字符串
        //得到子串,subSequence的end不能超出范围,才能截取到子串
        if (end <= stringBuffer.length()) {
            CharSequence charSequence = stringBuffer.subSequence(start, end);
            //和给定的字符串比较
            boolean b = charSequence.equals(charSequence);
            //匹配到一样的,执行替换
            if (b) {
                //遍历替换字符串
                for (int i = 0; i < len; i++) {
                    stringBuffer.setCharAt(start, str2.charAt(i));
                    start++;
                }
            }
        }
        //不存在,或者截取到的子串长度不够
        if (start == -1) {
            return stringBuffer;
        }

        return stringBuffer;
    }

    //实现替换所有
    public static StringBuffer repalceAll(StringBuffer stringBuffer, String str1, String str2) {
        int start = stringBuffer.indexOf(str1);
        int len = stringBuffer.length();
        int count = (len - start) / 2;
        for (int i = 0; i < count; i++) {
            stringBuffer = repalce(stringBuffer, str1, str2);
        }
        return stringBuffer;
    }
}

运行结果:
实现一个字符串替换_第1张图片

你可能感兴趣的:(java,编程,字符串)