Java examples for java.lang:String Replace
Write code to replace a string using while loop
//package com.java2s; public class Main { public static void main(String[] argv) { String source = "java2s.com"; String subject = "java2s.com"; String object = "java2s.com"; System.out.println(replace(source, subject, object)); }/*from ww w .ja va2 s . co m*/ public static String replace(String source, String subject, String object) { StringBuffer rtnStr = new StringBuffer(); String preStr = ""; String nextStr = source; String srcStr = source; while (srcStr.indexOf(subject) >= 0) { preStr = srcStr.substring(0, srcStr.indexOf(subject)); nextStr = srcStr.substring( srcStr.indexOf(subject) + subject.length(), srcStr.length()); srcStr = nextStr; rtnStr.append(preStr).append(object); } rtnStr.append(nextStr); return rtnStr.toString(); } }