Java中不区分大小写的replace()方法(使用indexOf)

时间:2014-06-06 20:47:15

标签: java string replace substring indexof

我需要一个replace()方法,它可以用不区分大小写的方式替换haystack String中的一个String String。我还需要在没有任何正则表达式的情况下完成此操作。我找不到任何这样的方法,所以我写了自己的方法。这个问题是要记录它,以防其他人发现它将来有用。如果可以进行任何改进(不使用String.replace),请随时提出建议。

2 个答案:

答案 0 :(得分:1)

public static String replace(String needle, String hayStack, String replacement)
{
    String origNeedle = needle;
    String origHayStack = hayStack;

    needle = origNeedle.toLowerCase();
    hayStack = origHayStack.toLowerCase();

    int hayStackLen = hayStack.length();
    int needleLen = needle.length();
    int from = 0;
    int to;

    String stuffBeforeNeedle;
    StringBuilder output = new StringBuilder();

    do
    {
        to = hayStack.indexOf(needle, from);
        if (to == -1)
            to = hayStackLen;

        stuffBeforeNeedle = hayStack.substring(from, to);
        output.append(stuffBeforeNeedle);

        if (to < hayStackLen)
            output.append( replacement );

        from = hayStack.indexOf(needle, to) + needleLen;
    }
    while (to < hayStackLen);

    return output.toString();
}

答案 1 :(得分:0)

public static void main(String[] args) throws IOException, ApplicationException, InterruptedException
{
    String output = "";

    String haystack = "This is the end. The beautiful EnD.  No safety or surprise, the eND. La la la!";
    String needle = "eNd";

    String replacement = "beginning";

    String searchHaystack = haystack.toLowerCase();
    String searchNeedle = needle.toLowerCase();

    int substringStart = 0;
    int beginningOfNeedle = -1;
    while(true)
    {           
        // Finds the first needle in the haystack, starting the search just after the last one we found.
        // (On the first iteration, we start from the first character).
        beginningOfNeedle = searchHaystack.indexOf(searchNeedle, ++beginningOfNeedle);

        // If we can't find another needle, we're done.
        if(beginningOfNeedle == -1)
            break;          

        // If we found a needle, we add to our output the substring of haystack
        // that starts from substringStart and goes right up to the beginning of the needle
        // we just found.
        output += haystack.substring(substringStart, beginningOfNeedle);
        // We also add the replacement text.
        output += replacement;

        // The next substring will start right at the end of the needle.
        substringStart = beginningOfNeedle + needle.length();
    }
    // We add the last substring (which runs through the end of the haystack)
    // to the output.
    output += haystack.substring(substringStart);


    System.out.println(output);
}