Java String Program · S21
Replace Spaces with %20 Without replace() in Java
Write each character to a new string, emitting %20 wherever a space appears. The classic version sizes a char[] exactly and fills it from the back.
Problem Statement
Write a method that returns a copy of a string in which every space is replaced by the three characters %20, without calling String.replace() or replaceAll().
Every space is replaced, including leading and repeated ones. A string with no spaces is returned unchanged.
Input/Output Examples
"open the door"Output"open%20the%20door"Explanation: both spaces become %20." a"Output"%20%20a"Explanation: each of the two spaces is replaced."nospace"Output"nospace"Explanation: nothing changes.Visual Explanation
"open the door": each space (amber) becomes three characters, so the result is 2 × 2 = 4 characters longer.Each space grows the string by two characters. Counting the spaces first gives the exact output length, which is how the char[] version allocates its array once.
Approaches
The first approach appends to a builder. The second sizes an array exactly and fills it from the end.
Approach 1: StringBuilder Loop (Recommended)
Idea: copy characters into a StringBuilder, appending "%20" in place of each space.
- Create a
StringBuilderwith some spare capacity. - For a space, append
"%20"; for anything else, append the character. - Return
toString().
Time: O(n) · Space: O(n).
Approach 2: Exact char[] Filled From the End
Idea: count the spaces, allocate an array of length n + 2 × spaces, then copy from the last character to the first.
- Count the spaces.
- Create a
char[]of the exact final length. - Read from the end of the input; write
'0','2','%'for a space, or the character itself. - Build the result from the array.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: StringBuilder Loop (Recommended)
The simplest correct solution, and the one to use in real code.
public class UrlifyBuilder {
// Copies every character, writing "%20" in place of each space
static String encodeSpaces(String text) {
StringBuilder result = new StringBuilder(text.length() + 16);
for (char c : text.toCharArray()) {
if (c == ' ') {
result.append("%20");
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String[] inputs = {"open the door", " a", "nospace"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + encodeSpaces(s) + "\"");
}
}
}
"open the door" -> "open%20the%20door" " a" -> "%20%20a" "nospace" -> "nospace"
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Exact char[] Filled From the End
Filling from the back is what makes the in-place version of this problem possible, when the buffer already has room at the end.
public class UrlifyCharArray {
// Counts the spaces, sizes the array exactly, then fills it from the end
static String encodeSpaces(String text) {
int spaces = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ') {
spaces++;
}
}
char[] result = new char[text.length() + 2 * spaces];
int write = result.length - 1;
for (int read = text.length() - 1; read >= 0; read--) {
char c = text.charAt(read);
if (c == ' ') {
result[write--] = '0';
result[write--] = '2';
result[write--] = '%';
} else {
result[write--] = c;
}
}
return new String(result);
}
public static void main(String[] args) {
String[] inputs = {"open the door", " a", "nospace"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> \"" + encodeSpaces(s) + "\"");
}
}
}
"open the door" -> "open%20the%20door" " a" -> "%20%20a" "nospace" -> "nospace"
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| StringBuilder Loop | O(n) | O(n) |
| Exact char[] Filled From the End | O(n) | O(n) |
Here n is the length of the input. Both approaches read every character once and produce an output of length n + 2s, where s is the number of spaces.
Interview Tips and Recommended Approach
- Explain why to fill from the end. If the array already contains the text with spare room at the back, writing from the front would overwrite characters you have not read yet.
- Write the three characters in reverse order when going backwards:
'0', then'2', then'%'. - Avoid string concatenation in the loop.
result += "%20"creates a new string each time. - Mention real URL encoding.
URLEncoder.encode()handles every special character, but it turns spaces into+, not%20.
Recommended Approach: StringBuilder Loop
Why: it is clear, linear and needs no index arithmetic. In an interview, mention the backward-filling version when the question is about an in-place buffer.