Java - Write code to replace a string using for loop

Requirements

Write code to replace a string using for loop

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String sourceStr = "book2s.com";
        String findStr = "o";
        String replaceStr = "O";
        System.out.println(replace(sourceStr, findStr, replaceStr));
    }//from w w  w . j  ava 2  s.c o  m

    public static String replace(String sourceStr, String findStr,
            String replaceStr) {
        if (sourceStr == null) {
            return "";
        }
        int i = 0;
        StringBuffer stringbuffer = new StringBuffer();
        for (int j = sourceStr.indexOf(findStr, i); j >= 0; j = sourceStr
                .indexOf(findStr, i)) {
            stringbuffer.append(sourceStr.substring(i, j));
            stringbuffer.append(replaceStr);
            i = j + findStr.length();
        }

        if (i <= sourceStr.length()) {
            stringbuffer.append(sourceStr.substring(i, sourceStr.length()));
        }
        return stringbuffer.toString();
    }
}

Related Example