static void Main(string[] args) { //重復分割符問題的實踐和演示 //實踐運用的場景||、|同為分割符,2替換為空時出現的|||情況 string content = "1234567890"; string replaceOptions = "1|a||2|||3|||4|c"; Console.WriteLine(replaceContent(content, replaceOptions)); Console.ReadKey(); }
/** * 適用於1|a||2|||3|c模式分割,兼容多個|||的情況 **/ public static string replaceContent(string content, string filterWord) { ArrayList filterWhiteSpace = new ArrayList(); spliteMuliSymbol(filterWord, ref filterWhiteSpace); for (int i = 0; i < filterWhiteSpace.Count; i++) { string[] replaceArr = filterWhiteSpace[i].ToString().Split('|'); content = Regex.Replace(content, replaceArr[0], replaceArr[1]); } return content; }
public static void spliteMuliSymbol(string filterWord, ref ArrayList filterWhiteSpace) { //判斷是否存在替換為空的情況 if (filterWord.Contains("|||")) { int whiteSpaceIndex = filterWord.IndexOf("|||"); ArrayList arrHalf = new ArrayList(); string firstHalf = filterWord.Substring(0, whiteSpaceIndex + 1); string latterHalf = filterWord.Substring(whiteSpaceIndex + 3); arrHalf.Add(firstHalf); arrHalf.Add(latterHalf); for (int i = 0; i < arrHalf.Count; i++) { spliteMuliSymbol(arrHalf[i].ToString(), ref filterWhiteSpace); } } else { string[] filterWordArray = Regex.Split(filterWord, @"\|\|"); foreach (string temp in filterWordArray) { filterWhiteSpace.Add(temp); } } }