首页 > 解决方案 > 在字符串字符说明中插入 %20

问题描述

嗨,我正在做一个破解编码我已经编写了一个解决方案,通过阅读用简单的英语解释的答案,但是我不明白一行代码。

问题

将所有空格替换为“%20”,在文本末尾添加空格以容纳新符号

输入:“Mr John Smith”,13 输出:Mr%20John%20Smith

我的解决方案

*static void replaceSpaces(char[] arr,int trueLength)
{
   int spaces = 0;
   int newLength = 0;
   int length = 0;
   for(int i = 0; i<trueLength; ++i)
   {
       if(arr[i] == ' ')
       {
           ++spaces;
       }
       newLength = trueLength +spaces*2; // We already have one space, so we need to add 2 extra spaces to fit the %20 symbol
   }
    for(int i = trueLength-1; i>=0; i--)
    {
        if(arr[i] == ' ')
        {
            arr[newLength-1] = '0';
            arr[newLength-2] = '2';
            arr[newLength-3] = '%';
            newLength = newLength - 3;    

        }
        else
        {
            arr[newLength-1] = arr[i];
            newLength = newLength - 1;
        }
    }
    System.out.println(arr);
}*




  

我不明白为什么我们需要这行代码(newLength = newLength - 3),我认为我们需要它,因为在我们用符号删除空格后,我们减去 3 到下一个空格,这是正确的吗?

标签: arraysstringalgorithmin-place

解决方案


没错,如果你的意思是:到下一个空白处写一个新字符。存在代码newLength = newLength - 3;行是因为您需要跳过 3 个字符('0'、'2' 和 '%')。否则你会覆盖它们。

我必须提到您的代码非常典型,因为您正在向后填充数组。


推荐阅读