Here you can find the source of replace(String source, String oldChars, String newChars)
Parameter | Description |
---|---|
source | a parameter |
oldChars | a parameter |
newChars | a parameter |
public static String replace(String source, String oldChars, String newChars)
//package com.java2s; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { /**/*from w ww. j a v a 2 s . co m*/ * Method replace. Replaces substrings within one string with another string * * @param source * @param oldChars * @param newChars * @return String */ public static String replace(String source, String oldChars, String newChars) { if (source == null) return null; if (oldChars == null || oldChars.length() == 0 || newChars == null || source.indexOf(oldChars) == -1) return source; // Exact match if (source.equals(oldChars)) return newChars; // Split into list of tokens delimited on old characters and create new buffer using the same tokens but // with the new characters inserted between the tokens. StringBuffer buffer = new StringBuffer(source.length()); List<String> tokens = split(source, oldChars); boolean firstToken = true; Iterator<String> iter = tokens.iterator(); while (iter.hasNext()) { String token = iter.next(); if (!firstToken && newChars.length() > 0) buffer.append(newChars); buffer.append(token); firstToken = false; } return buffer.toString(); } /** * Method split. Splits a string into multiple strings as delimited by the 'delimiter' string * * @param input * @param delimiter * @return List */ public static List<String> split(String input, String delimiter) { if (input == null) return null; List<String> splitList = new ArrayList<String>(16); if (input.length() == 0) return splitList; int startIndex = 0; int endIndex; do { endIndex = input.indexOf(delimiter, startIndex); if (endIndex > -1) { // Extract the element and adjust new starting point splitList.add(input.substring(startIndex, endIndex)); startIndex = endIndex + delimiter.length(); } else { // Last element splitList.add(input.substring(startIndex)); } } while (endIndex > -1); // Return the list return splitList; } }