可能是一个愚蠢的问题,但我已经搜索和搜索,似乎无法找到一种方法,使用for循环替换字符串中的子字符串,而不是内置在java函数,如replace,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);
提前致谢!!
答案 0 :(得分:0)
我希望这是作业。所以给你伪代码。 `
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();
}
答案 1 :(得分:0)
再次查看您的代码。当counter为2时,下面将抛出一个ArrayIndexOutOfBoundException
if(find[counter] == replace[counter])
以下循环永远不会执行,j被初始化为计数器+ 1,但运行循环的条件是j应该小于计数器
for(int j=counter+1; j<counter; counter++)
同样适用于内循环
for(int h=j+1; h<j; h++)
答案 2 :(得分:0)
我认为这可能会对您有所帮助:
StringBuilder replacedString = new StringBuilder();
for(int counter = 0; counter<replace.length; counter++){
boolean charFound = false;
for(int j=0; j<find.length; j++){
if(find[j]==replace[counter])
charFound = true;
}
if(!charFound)
replacedString.append(replace[counter]);
}
System.out.println("Replaced string" + replacedString.toString());