arrays - 在字符串字符说明中插入 %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 到下一个空格,这是正确的吗?
解决方案
没错,如果你的意思是:到下一个空白处写一个新字符。存在代码newLength = newLength - 3;
行是因为您需要跳过 3 个字符('0'、'2' 和 '%')。否则你会覆盖它们。
我必须提到您的代码非常典型,因为您正在向后填充数组。
推荐阅读
- ios - UICollectionView 从左到右读取多行
- node.js - 需要扫描数据库并显示消息或更新项目
- gradle - Gradle (Kotlin DSL) 测试未执行
- jekyll - Jekyll 内部帖子链接
- c - C区分函数和结构
- powershell - Powershell 在 Outlook 中创建另一个文件夹并移动电子邮件
- db2 - 查找员工表 db2 大型机的第 n 个最大薪水
- r - 在 Shiny Dashboard 的 tabpabel 中调整 ggplot 条形图的高度
- javascript - 当将数据推入数组时,只推入一个索引
- c# - 使用 WS-security Authentication 用户名使用 WS