替换空格

2019-03-01  本文已影响0人  flyinghat

题目

请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

        //简单粗暴的
        public string ReplaceSpace(string str)
        {
            var s = str.Replace(" ", "%20"); //新建一个字符串
            return s;
        }

        //此方法比上面的耗时,暂未知Replace源码
        public string ReplaceSpace2(string str)
        {
            var count = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ' ')
                {
                    count++;
                }
            }
            var le = str.Length + (count * 2);   //str.Length - count + (count * 3);
            var c = new char[le];
            var newIndex = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] != ' ')
                {
                    c[newIndex] = str[i];
                    newIndex++;
                }
                else
                {
                    c[newIndex] = '%';
                    c[++newIndex] = '2';
                    c[++newIndex] = '0';
                    newIndex++;
                }
            }
            return new string(c);
        }
上一篇 下一篇

猜你喜欢

热点阅读