Replaces all the occurrences of a given string with another string - Java java.lang

Java examples for java.lang:String Replace

Introduction

The following code shows how to Replaces all the occurrences of a given string with another string .

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sInString = "java2s.com";
        String sReplaceWhat = "0";
        String sReplaceWith = "o";
        System.out//from w  ww  .ja  v a  2 s . c o  m
                .println(replaceAll(sInString, sReplaceWhat, sReplaceWith));
    }

    /**
     * Replaces all the occurrences of a given string with another string
     * 
     * @param sInString
     *            The original string
     * @param sReplaceWhat
     *            The string to replace
     * @param sReplaceWith
     *            The string to replace with
     * @return The result of the replacement.
     */
    public static String replaceAll(String sInString, String sReplaceWhat,
            String sReplaceWith) {
        int iIndex = 0;

        while ((iIndex = sInString.indexOf(sReplaceWhat)) != -1) {
            String sPrefix = "";

            if (iIndex != 0)
                sPrefix = sInString.substring(0, iIndex);

            String sPostfix = "";

            if (iIndex + sReplaceWhat.length() < sInString.length())
                sPostfix = sInString.substring(
                        iIndex + sReplaceWhat.length(), sInString.length());

            sInString = sPrefix + sReplaceWith + sPostfix;
        }

        return sInString;
    }
}

Related Tutorials