面试谜语(字符串操作)——需要解释

interview riddle (string manipulation) - explanation needed

我正在学习面试,遇到一个问题+解决方案。 我在解决方案中遇到一行问题,希望这里有人可以解释一下。

问题:

Write a method to replace all spaces in a string with ‘%20’.

解决方法:

public static void ReplaceFun(char[] str, int length) {
    int spaceCount = 0, newLength, i = 0;
    for (i = 0; i < length; i++) {
        if (str[i] == ‘ ‘) {
            spaceCount++;
        }
    }
    newLength = length + spaceCount * 2;
    str[newLength] = ‘[=10=]’;
    for (i = length - 1; i >= 0; i--) {
        if (str[i] == ‘ ‘) {
            str[newLength - 1] = ‘0’;
            str[newLength - 2] = ‘2’;
            str[newLength - 3] = ‘%’;
            newLength = newLength - 3;
        } else {
            str[newLength - 1] = str[i];
            newLength = newLength - 1;
        }
    }
}

我的问题出在第 9 行。他怎么能将 str[newLength] 设置为“\0”?或者换句话说,他如何在不先分配内存或类似的情况下接管所需的内存量? 他 运行 是不是记错了?!

假设这实际上意味着在 C 中(private static 不是有效的 C 或 C++),他们不能,因为它是写的。他们永远不会分配一个新的 str ,它的长度足以容纳旧字符串加上 %20 扩展。

我怀疑这个问题还有一个额外的部分,那就是 str 已经足够长来容纳扩展的 %20 数据,而 lengthlength 的长度str 中的字符串,不包括零终止符。

这是有效代码,但不是好代码。您对我们正在覆盖初始 str[] 的边界的评估是完全正确的。这可能会导致一些不需要的副作用,具体取决于被覆盖的内容。