当前位置: 移动技术网 > IT编程>开发语言>c# > 字符串替换Replace仅替换第一个字符串匹配项

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下: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;
        }

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网