This was a small coding challenge proposed at my school. The problem is:
Given a string (or URL), replace the white-spaces inside of the string with
%20, but any spaces on the outside should not be included.For example, input
" Mr John Smith "would return"Mr%20John%20Smith".
I have completed this challenge successfully using the code below. My question is, is there any way to improve the efficiency? I believe the complexity is currently \$O(2n) = O(n)\$ given the 2 for loops. I do not want to use any libraries or functions like str.replace(). But I'm assuming there is a better way than trimming and then counting the whitespace.
public class URL {
/**
* @description URLify ~ A small method that makes a string with spaces URL Friendly!
* @param str
* @param length
* @return String
*/
public static String URLify(String str) {
str = str.trim();
int length = str.length();
int trueL = length;
if(str.contains(" ")) {
for(int i = 0; i < length; i++) {
if(str.charAt(i) == ' ') {
trueL = trueL + 2;
}
}
char[] oldArr = str.toCharArray();
char[] newArr = new char[trueL];
int x = 0;
for(int i = 0; i < length; i++) {
if(oldArr[i] == ' ') {
newArr[x] = '%';
newArr[x+1] = '2';
newArr[x+2] = '0';
x += 3;
} else {
newArr[x] = oldArr[i];
x++;
}
}
str = new String(newArr, 0, trueL);
}
return str;
}
public static void main(String[] args) {
String str = " https://google.com/ testing .pdf ";
str = URLify(str);
System.out.print(str);
}
}
Note: I am looking for any criticism. I would really like to improve my skills in general.
str.trim().replaceAll(" ", "%20"), but I guess that is kind of cheating? \$\endgroup\$str.replace()" but a library function likestr.trim()is ok? 50% of the requirement is handled by a library function. Tip: be consistent. \$\endgroup\$