可能是一个愚蠢的问题,但我搜索了又搜索,似乎找不到一种使用 for 循环替换字符串中的子字符串的方法,而不是内置于 java 函数(如替换、replaceAll 等)中。我'我尝试创建自己的,但最终得到了大约 4 个 for 循环,但最终没有成功。知道如何使用循环创建替换函数而不是内置替换函数吗?
我添加了我的代码,试图给出我正在使用的变量的想法。
public boolean replaceString(String oldString, String newString){
String D = "xx";
char[] find = "BC".toCharArray();
char[] replace ="ABCDE".toCharArray();
String rep = new String(replace);
String fin = new String(find);
String E ="";
String F = "";
for(int counter = 0; counter<replace.length; counter++){
if(find[counter] == replace[counter]){
for(int j=counter+1; j<counter; counter++){
E += rep.charAt(j);
for(int h=j+1; h<j; h++){
if(find[h] == replace[h]){
for(int k=h+1; k<h; k++){
F += rep.charAt(k);
}
}
}
}
}
}
String finReplace = new String(E + D + F);
System.out.println("REPLACE");
System.out.println(finReplace);
提前致谢!!
最佳答案
我希望这是为了作业。所以给你伪代码。 `
public static String replaceString(
final String inputString,
final String searchString,
final String newString)
{
if ( searchString==null || searchString.equals("") ) {
throw new IllegalArgumentException("Search string must have some content");
}
final StringBuilder result = new StringBuilder ();
int startIdx = 0;
int idxOld = 0;
while ((idxOld = inputString.indexOf(searchString, newString)) >= 0) {
result.append( inputString.substring(startIdx, idxOld) );
result.append( newString);
startIdx = idxOld + searchString.length();
}
//the final chunk will go to the end of aInput
result.append( inputString.substring(startIdx) );
return result.toString();
}
关于java - 替换没有内置函数 Java 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941787/