Skip to content

Instantly share code, notes, and snippets.

@allanx2000 allanx2000/ArrayStringReplace? Secret
Created Dec 22, 2017

Embed
What would you like to do?
Cracking 1.3
package cracking.ch1;
public class P1_3 {
private static final char SPACE = ' ';
private static final String REPLACEMENT = "%20";
public static void main(String[] args) {
String input = "Mr John Smith";
String paddedInput = createPadded(input, SPACE,REPLACEMENT);
System.out.println("'" + paddedInput + "'");
String url = replaceAll(paddedInput, SPACE,REPLACEMENT);
System.out.println("'" + url + "'");
}
private static String replaceAll(String text, char chr, String replacement) {
int offset = 0;
char[] chars = text.toCharArray();
for (int i = chars.length - 1; i >= 0; i--)
{
if (chars[i] == chr)
offset++;
else
break;
}
for (int i = chars.length - 1 - offset; i >= 0; i--)
{
if (chars[i] == chr)
{
for (int x = replacement.length() - 1; x>= 0; x--)
{
chars[i + offset] = replacement.charAt(x);
offset--;
}
//Make up for the exist char it replaced
offset++;
}
else
chars[i + offset] = chars[i];
}
return new String(chars);
}
private static String createPadded(String text, char chr, String replacement) {
int counter = 0;
for (char c : text.toCharArray())
{
if (c == chr)
counter++;
}
int extraSpace = (replacement.length() - 1)*counter;
char[] array = new char[text.length() + extraSpace];
for (int i = 0; i < text.length(); i++)
{
array[i] = text.charAt(i);
}
for (int i = text.length(); i < array.length; i++)
{
array[i] = chr;
}
return new String(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.