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的算法吧,说出这个,肯定满分

猜你喜欢

转载自blog.csdn.net/qq_38056704/article/details/86485421