欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字符串替换Replace仅替换第一个字符串匹配项

程序员文章站 2024-02-24 08:12:10
复制代码 代码如下:public static string replace(string source, string match, string replacement...

复制代码 代码如下:

public static string replace(string source, string match, string replacement)
        {
            char[] sarr = source.tochararray();
            char[] marr = match.tochararray();
            char[] rarr = replacement.tochararray();
            int idx = indexof(sarr, marr);
            if (idx == -1)
            {
                return source;
            }
            else
            {
                return new string(sarr.take(idx).concat(rarr).concat(sarr.skip(idx + marr.length)).toarray());
            }
        }
        /// <summary>
        /// 查找字符数组在另一个字符数组中匹配的位置
        /// </summary>
        /// <param name="source">源字符数组</param>
        /// <param name="match">匹配字符数组</param>
        /// <returns>匹配的位置,未找到匹配则返回-1</returns>
        private static int indexof(char[] source, char[] match)
        {
            int idx = -1;
            for (int i = 0; i < source.length - match.length; i++)
            {
                if (source[i] == match[0])
                {
                    bool ismatch = true;
                    for (int j = 0; j < match.length; j++)
                    {
                        if (source[i + j] != match[j])
                        {
                            ismatch = false;
                            break;
                        }
                    }
                    if (ismatch)
                    {
                        idx = i;
                        break;
                    }
                }
            }
            return idx;
        }