Java examples for java.lang:String Replace
change string by replacing
//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(); } }