美文网首页
替换空格

替换空格

作者: flyinghat | 来源:发表于2019-03-01 23:41 被阅读0次

    题目

    请实现一个函数,将一个字符串中的每个空格替换成“%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);
            }
    

    相关文章

      网友评论

          本文标题:替换空格

          本文链接:https://www.haomeiwen.com/subject/zdjsuqtx.html