change string by replacing - Java java.lang

Java examples for java.lang:String Replace

Description

change string by replacing

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String in = "java2s.com";
        String oldPat = "com";
        String newPat = "COM";
        System.out.println(change(in, oldPat, newPat));
    }/*from   w  ww  .  j a  v a  2 s. co  m*/

    private static String change(String in, String oldPat, String newPat) {
        if (oldPat.length() == 0)
            return in;
        if (oldPat.length() == 1 && newPat.length() == 1)
            return in.replace(oldPat.charAt(0), newPat.charAt(0));

        int lastIndex = 0;
        int newIndex = 0;
        StringBuffer newString = new StringBuffer();
        for (;;) {
            newIndex = in.indexOf(oldPat, lastIndex);
            if (newIndex != -1) {
                newString.append(in.substring(lastIndex, newIndex) + newPat);
                lastIndex = newIndex + oldPat.length();
            } else {
                newString.append(in.substring(lastIndex));
                break;
            }
        }
        return newString.toString();
    }
}

Related Tutorials