1

可能是一个愚蠢的问题,但我已经搜索和搜索,似乎无法找到一种方法来使用 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);

提前致谢!!

4

3 回答 3

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());
于 2013-09-22T09:34:50.863 回答
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();

}

于 2013-09-22T08:39:33.350 回答
0

再看看你的代码。当计数器为 2 时,下面将抛出 ArrayIndexOutOfBoundException

if(find[counter] == replace[counter])

下面的循环永远不会执行并且 j 被初始化为 counter+1,但是运行循环的条件是 j 应该小于 counter

for(int j=counter+1; j<counter; counter++)

内循环也是如此

for(int h=j+1; h<j; h++)
于 2013-09-22T09:11:06.550 回答