我需要java replaceall方法的算法和ı想写这个方法只使用charAt和长度方法。我试试,但我没有做它请帮助我。抱歉我的英语不好。
答案 0 :(得分:-1)
您的问题不明确。
我不知道你想要什么。您是否希望代码从其他String中替换 string 或 character ?这是你的简单例子。
public static String replace(String source,char oldChar,char newChar){
char[] temp = source.toCharArray();
StringBuilder result = new StringBuilder();
for (char c : temp) {
if(c == oldChar){
result.append(newChar);
}else result.append(c);
}
return result.toString();
}
也许这是你需要的解决方案,但我不明白你的问题:/
public static String replaceStr(String source, String oldSR, String newSR) {
List<Integer> positions = findPosition(source, oldSR);
int lengthOldSr = oldSR.length();
for (Integer position : positions) {
StringBuilder result = new StringBuilder("");
int lengthSource = source.length();
for (int i = 0; i < lengthSource; i++) {
if (position == i) {
result.append(newSR);
i += lengthOldSr - 1;
} else {
result.append(source.charAt(i));
}
}
source = result.toString();
}
return source;
}
public static List<Integer> findPosition(String source, String oldSR) {
int lengthOld = oldSR.length();
int lengthSource = source.length();
List<Integer> positions = new ArrayList<>();
for (int i = 0; i < lengthSource; i++) {
int count = 0;
for (int j = 0; j < lengthOld; j++) {
if ((j + i < lengthSource) && source.charAt(j + i) == oldSR.charAt(j)) {
count++;
}
}
if (count == lengthOld) {
positions.add(i);
}
}
positions.sort(Comparator.reverseOrder());
return positions;
}
}
INPUT:来源 TUYENDEV 123 TUYENDEV 123 STACKOVER ,旧 123 , new 456
输出:TUYENDEV 456 TUYENDEV 456 STACKOVER