-
-
Save allanx2000/38521068886963e1199e0567f9ccbe03 to your computer and use it in GitHub Desktop.
Cracking 1.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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