|
| 1 | +using System.Collections.Generic; |
| 2 | +using System.Linq; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace Flier.Toolbox.Text |
| 6 | +{ |
| 7 | + public class FastReplace |
| 8 | + { |
| 9 | + private readonly Dictionary<char, List<KeyValuePair<string, string>>> Dictionary_Head; |
| 10 | + |
| 11 | + /// <summary> |
| 12 | + /// Replace a lot of string |
| 13 | + /// </summary> |
| 14 | + /// <param name="Dictionary"></param> |
| 15 | + public FastReplace(Dictionary<string, string> Dictionary) |
| 16 | + { |
| 17 | + Dictionary_Head = Dictionary.GroupBy(x => x.Key.First()).ToDictionary(x => x.Key, x => x.ToList()); |
| 18 | + } |
| 19 | + public string ReplaceAll(string source) |
| 20 | + { |
| 21 | + StringBuilder sb = new StringBuilder(source.Length); |
| 22 | + char[] key = Dictionary_Head.Keys.ToArray(); |
| 23 | + int indexPass, indexNow = 0; |
| 24 | + indexPass = indexNow; |
| 25 | + indexNow = source.IndexOfAny(key, indexNow); |
| 26 | + int i; |
| 27 | + while (indexNow != -1) |
| 28 | + { |
| 29 | + sb.Append(source.Substring(indexPass, indexNow - indexPass)); |
| 30 | + var _dic = Dictionary_Head[source[indexNow]]; |
| 31 | + bool replaced = false; |
| 32 | + foreach (var a in _dic) |
| 33 | + { |
| 34 | + if (indexNow + a.Key.Length > source.Length) |
| 35 | + continue; |
| 36 | + bool equal = true; |
| 37 | + for (i = 0; i < a.Key.Length; i++) |
| 38 | + if (source[indexNow + i] != a.Key[i]) |
| 39 | + { |
| 40 | + equal = false; |
| 41 | + break; |
| 42 | + } |
| 43 | + if (!equal) |
| 44 | + continue; |
| 45 | + sb.Append(a.Value); |
| 46 | + indexNow += a.Key.Length; |
| 47 | + replaced = true; |
| 48 | + break; |
| 49 | + } |
| 50 | + if (!replaced) |
| 51 | + { |
| 52 | + sb.Append(source.Substring(indexNow, 1)); |
| 53 | + indexNow++; |
| 54 | + } |
| 55 | + indexPass = indexNow; |
| 56 | + indexNow = source.IndexOfAny(key, indexNow); |
| 57 | + } |
| 58 | + sb.Append(source.Substring(indexPass, source.Length - indexPass)); |
| 59 | + return sb.ToString(); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments