亲宝软件园·资讯

展开

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

人气:0
想了解字符串替换Replace仅替换第一个字符串匹配项的相关内容吗,在本文为您仔细讲解字符串替换Replace仅替换第一个匹配项的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:字符串替换,replace,字符串匹配,下面大家一起来学习吧。

复制代码 代码如下:

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;
        }

加载全部内容

相关教程
猜你喜欢
用户评论