写工具的时候遇到个需求c#写了一个替换字符串限定次数的

2024-09-27  本文已影响0人  吉凶以情迁
     public static String ReplaceString(string line, string findText, string replaceText, int count, out bool isSuccess, bool fromEnd = false, bool ignoreCase = false)
        {
            isSuccess = false;
            int seek =fromEnd?line.Length: 0;
            if (findText == replaceText) {//null
                throw new Exception("不能处理被替换字符也包含要被替换的包含的字符串!");
            }
            int a = 0;
            int index = -1;
            while (true) {
                bool condi;
                if (ignoreCase) {
                    condi = (fromEnd ? index = line.ToLower().LastIndexOf(findText.ToLower(), seek) : index = line.ToLower().IndexOf(findText.ToLower(), seek)) >= 0 && a < count;

                }
                else {
                    condi = (fromEnd ? index = line.LastIndexOf(findText, seek) : index = line.IndexOf(findText, seek)) >= 0 && a < count;
                }

                if (!condi) {
                    break;
                }
                string start = "";
                string end = "";
                if (index > 0) {
                    start = line.Substring(0, index);



                }
                seek = index + replaceText.Length;
                if (index + findText.Length < line.Length) ;
                {
                    end = line.Substring(index + findText.Length);

                }
                line = start + replaceText + end;
                isSuccess = true;
                a++;
            }
            return line;
        }
上一篇 下一篇

猜你喜欢

热点阅读