-
Notifications
You must be signed in to change notification settings - Fork 28
/
Urlifier.java
36 lines (29 loc) · 1.02 KB
/
Urlifier.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.anthonynsimon.algorithms.strings;
public final class Urlifier {
public static String urlify(String url) {
// Count how many spaces are there
int numberOfSpaces = 0;
for (int i = 0; i < url.length(); i++) {
if (url.charAt(i) == ' ') {
numberOfSpaces += 1;
}
}
if (numberOfSpaces > 0) {
// Prepare a new Char[] with enough space for the new chars
char[] newUrl = new char[url.length() + (numberOfSpaces * 2)];
int copyIndex = 0;
for (int i = 0; i < url.length(); i++) {
char currentChar = url.charAt(i);
if (currentChar == ' ') {
newUrl[copyIndex++] = '%';
newUrl[copyIndex++] = '2';
newUrl[copyIndex++] = '0';
} else {
newUrl[copyIndex++] = currentChar;
}
}
url = String.copyValueOf(newUrl);
}
return url;
}
}