我的自定义查找和替换代码无法正常工作

时间:2014-05-23 19:09:12

标签: java replace

我已经创建了两种自定义查找和替换方法,但它们无法正常工作。

这是我的查找和替换代码:

public final class StringTools {
    public static String replaceAll(String text, String replace, String replacement) {
        if (replace == replacement)
            return text;

        String currentText = null;
        String newText = text;
        do {
            currentText = newText;
            newText = replaceFirst(newText, replace, replacement);
        } while (currentText != newText);
        return newText;
    }

    public static String replaceFirst(String text, String replace, String replacement) {
        int found = 0;
        int foundAt = -1;

        // Loop through each char
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            // Does char match replace char?
            if (replace.charAt(found) == c) {
                // We found another match
                found++;

                // Have we found the entire replace text?
                if (found == replace.length()) {
                    // Mark location we found match first at
                    foundAt = i - found + 1;
                    break;
                }
            }
        }


        // Did we get a match?
        if (foundAt != -1) {
            // Replace text
            return text.substring(0, foundAt) + replacement    + text.substring(foundAt + replace.length(), text.length());
        }
        return text;
    }
}

我尝试使用此代码的大多数尝试都获得了成功的结果。但是,我发现了一个我的代码失败的情况,但我不确定为什么......

以下代码:

public static void main(String[] args) {
    String text = "{r}0{0}/{r} 10 players";

    text = StringTools.replaceAll(text, "{0}", "[test]");

    System.out.println(text);
}

然而,这输出:

{r} 0 [测试] / [测试] 10名玩家

正如您所看到的,它取代了第一个&#39; {0}&#39;与预期一样,但由于某种原因,它也取代了&#39; {r}&#39;。

任何帮助将不胜感激!干杯! :)

0 个答案:

没有答案