//методы public static string Minify(string htmlText, int targetLength, ContentMinifyMode mode) { Dictionary<int, string> tags = new Dictionary<int, string>(); StringBuilder builder = RemoveTags(htmlText, tags); builder = MinifyText(builder, targetLength, mode); builder = RestoreTags(tags, builder); return builder.ToString(); }
private static int FindCutPosition( StringBuilder builder, int targetLength, ContentMinifyMode mode) { int? индексТочкиСправа = null; int? индексТочкиСлева = null; int? расстояниеДоТочкиСправа = null; int? расстояниеДоТочкиСлева = null; // ищем точку справа for (int i = targetLength; i < builder.Length; i++) { if (builder[i] == '.') { индексТочкиСправа = i; расстояниеДоТочкиСправа = i - targetLength; break; } } // ищем точку слева if (mode == ContentMinifyMode.ToClosestDot) { for (int i = targetLength; i >= 0; i--) { if (builder[i] == '.') { индексТочкиСлева = i; расстояниеДоТочкиСлева = targetLength - i; break; } } } // ищем ближайшую точку if (индексТочкиСправа != null || индексТочкиСлева != null) { if (индексТочкиСправа == null || расстояниеДоТочкиСлева < расстояниеДоТочкиСправа) { targetLength = индексТочкиСлева.Value + 1; } else { targetLength = индексТочкиСправа.Value + 1; } } return targetLength; }
private static StringBuilder MinifyText( StringBuilder builder, int targetLength, ContentMinifyMode mode) { if (builder.Length <= targetLength) { return builder; } if (mode != ContentMinifyMode.Strict) { targetLength = FindCutPosition(builder, targetLength, mode); } if (builder.Length > targetLength) { int lengthToCut = builder.Length - targetLength; builder = builder.Remove(targetLength, lengthToCut); } return builder; }