字符串函数扩展 replace,indexof

public static class StringExtensions
    {
        public static int IndexOfTimes(this string s, string value, int times)
        {
            return s.IndexOfTimes(value, 0, times);
        }
        public static int IndexOfTimes(this string s, string value, int startindex, int times)
        {
            if (string.IsNullOrEmpty(s)) return -1;
            startindex = startindex < 0 ? 0 : startindex;
            if (times <= 0)
                return -1;
            int at = 0;
            int count = 0;
            while (startindex < s.Length)
            {
                at = s.IndexOf(value, startindex);
                if (at == -1)
                    return -1;
                count++;
                if (count == times)
                    return at;
                startindex = at + 1;
            }
            return -1;
        }

        public static string ReplaceFirst(this string s, string oldValue, string newValue)
        {
            return s.ReplaceTime(oldValue, newValue, 1);
        }

        public static string ReplaceTime(this string s, string oldValue, string newValue, int times)
        {
            int pos=s.IndexOfTimes(oldValue, times);
            if (pos < 0)
                return s;
            if (string.IsNullOrEmpty(newValue))
                return "";

            s = s.Remove(pos, oldValue.Length);
            s = s.Insert(pos, newValue);
            return s;
        }
    }

posted @ 2010-05-13 13:00  尹庆超  阅读(370)  评论(0编辑  收藏  举报