题目

请实现一个函数,把字符串中的每个空格替换成%20。例如输入We are happy.,则输出We%20are%20happy.

解题思路

先遍历一遍,确认有多少空格,然后开辟数组,数组长度为原字符串长度+2*空格数量('%20'长度-' '长度),然后从后往前进行字符拷贝,遇到空格就替换成'%20'

代码实现

private static string ReplaceBlank(char[] input)
{
    var blankCount = input.Count(charItem => charItem == ' ');

    var newCharArray = new char[input.Length + (blankCount * 2)];
    var newIndex = newCharArray.Length - 1;
    for (var idx = input.Length - 1; idx >= 0; idx--)
    {
        var current = input[idx];
        if (current == ' ')
        {
            newCharArray[newIndex--] = '0';
            newCharArray[newIndex--] = '2';
            newCharArray[newIndex--] = '%';
            continue;
        }

        newCharArray[newIndex--] = input[idx];
    }

    return new string(newCharArray);
}