Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    public static String replace(String str, String target, String replacement) {
        StringBuilder sb = new StringBuilder(str);

        int index = sb.length();
        int lenTarget = target.length();
        while ((index = sb.lastIndexOf(target, index)) != -1) {
            sb.replace(index, index + lenTarget, replacement);
            index -= lenTarget;
        }

        return sb.toString();
    }

    public static String replace(String str, String[] targets, String[] replacements) {
        StringBuilder sb = new StringBuilder(str);

        int index, lenTarget;
        for (int i = 0; i < targets.length; i++) {
            index = sb.length();
            lenTarget = targets[i].length();
            while ((index = sb.lastIndexOf(targets[i], index)) != -1) {
                sb.replace(index, index + lenTarget, replacements[i]);
                index -= lenTarget;
            }
        }

        return sb.toString();
    }
}