天天看點

Spring源碼亮點(一)- - 字元串replace算法

StringUtil包下,通用replace方法

/**
	 * Replace all occurrences of a substring within a string with another string.
	 * 字元串替換
	 * @param inString   {@code String} to examine
	 * @param oldPattern {@code String} to replace
	 * @param newPattern {@code String} to insert
	 * @return a {@code String} with the replacements
	 */
	public static String replace(String inString, String oldPattern, @Nullable String newPattern) {
		if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
			return inString;
		}
		int index = inString.indexOf(oldPattern);
		if (index == -1) {
			// no occurrence -> can return input as-is
			return inString;
		}

		int capacity = inString.length();
		if (newPattern.length() > oldPattern.length()) {
			capacity += 16;
		}
		StringBuilder sb = new StringBuilder(capacity);

		int pos = 0;  // our position in the old string
		int patLen = oldPattern.length();
		while (index >= 0) {
			sb.append(inString.substring(pos, index));//0,oldPattern前一位
			sb.append(newPattern);//oldPattern開始的地方替換成newPattern
			pos = index + patLen;//這裡加完之後,是原來inString的oldPattern後一位
			index = inString.indexOf(oldPattern, pos);//新的oladPattern的位置(上面已經完成替換工作了,這裡可以了解成新的一段,重複以上步驟)
		}

		// append any characters to the right of a match
		sb.append(inString.substring(pos));//把最後的都加上去
		return sb.toString();
	}
           

非常精簡,一些面試題裡有問涉及replace的算法吧,說出這個,肯定滿分