题目
替换字符串中连续出现的指定字符串
java代码
package com.lizhouwei.chapter5;
/**
* @Description: 替换字符串中连续出现的指定字符串
* @Author: lizhouwei
* @CreateDate: 2018/4/23 22:39
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_6 {
public String replace(String str, String from, String to) {
char[] chars = str.toCharArray();
char[] charf = from.toCharArray();
int mi = 0;
int si = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == charf[mi++]) {
if (mi == charf.length) {
si = i;
while (mi-- != 0) {
chars[si--] = '0';
}
mi = 0;
}
} else {
mi = 0;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] != '0') {
sb.append(chars[i]);
}
if (chars[i] == '0' && (i == 0 || chars[i - 1] != '0')) {
sb.append(to);
}
}
return sb.toString();
}
//测试
public static void main(String[] args) {
Chapter5_6 chapter = new Chapter5_6();
String str1 = "123abcabc";
String str2 = "abc";
String str3 = "4567";
System.out.println("将123abcabc中abc替换为4567:" + chapter.replace(str1, str2, str3));
}
}
结果