Write code to replace substring only Once
//package com.book2s; public class Main { public static void main(String[] argv) { String template = "book2s.com"; String placeholder = "o"; String replacement = "O"; System.out.println(replaceOnce(template, placeholder, replacement)); }/*from ww w. j av a2s. co m*/ public static String replaceOnce(String template, String placeholder, String replacement) { int loc = template == null ? -1 : template.indexOf(placeholder); if (loc < 0) { return template; } else { return new StringBuffer(template.substring(0, loc)) .append(replacement) .append(template.substring(loc + placeholder.length())) .toString(); } } public static String toString(Object[] array) { int len = array.length; if (len == 0) return ""; StringBuffer buf = new StringBuffer(len * 12); for (int i = 0; i < len - 1; i++) { buf.append(array[i]).append(", "); } return buf.append(array[len - 1]).toString(); } }