HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Method to replace all spaces in a String with '%20'

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodallwithreplacespacesstring

Problem

Problem statement (extracted from cracking the coding interview):

Write a method to replace all spaces in a string with'%20'. You may assume that
the string has sufficient space at the end of the string to hold the additional
characters, and that you are given the "true" length of the string. (Note: if implementing
in Java, please use a character array so that you can perform this operation
in place.)

EXAMPLE
Input: "Mr John Smith

Output: "Mr%20Dohn%20Smith"

My Solution:

public class InterviewMain {

    public static void main(String[] args){

        //Q 1.4
        String str = "Example String with spaces           ";
        replaceSpaces(str);
    }

    public static void replaceSpaces(String str){

        int trueLength = getTrueLength(str);

        char[] strChar = str.toCharArray();
        int spaceCount = 0;
        int finalLength;

        //count the number of spaces in the original string
        for (int i=0; i=0; i--){
            if (strChar[i]!= ' ')break;
            count++;
        }
        return length-count;
    }

    private static int getInsertIndex(int i, int spaces){
        return (i + spaces*2);
    }
}


I was wondering if someone could review this and point out what I have done right and where I can improve upon. Thank you

Solution

It's important to pay attention to every bit of detail in the problem description:


Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

As you're implementing this in Java, your method should receive a char[] instead of a String. And if I interpret correctly, the "true" length is the length without the padding, and is an additional parameter, giving the signature:

void replaceSpaces(char[] input, int trueLength) { ... }


With this established, the implementation can be simplified:

  • No need for getTrueLength: it's a given



  • No need for calculating the final size, it's given by input.length



  • As @rolfl pointed out, the size of input is not 100% clear. The description only states that it has sufficient space. So indeed, we may need to calculate the final size.



  • The printing is unnecessary and should be removed, as it breaks the single responsibility of the method



Another improvement in the implementation is that you don't need to count the spaces. You can walk backward, tracking two positions in parallel:

  • The last position to write to (starts at input.length - 1)



  • The last position in the text (starts at trueLength - 1)



Walk backward as long as the text position is smaller than the end position. If you see a space, overwrite the the values at the position with %20. Otherwise simply copy the input.

void replaceSpaces(char[] input, int trueLength) {
    //int end = input.length - 1;
    int end = trueLength + (countSpaces(input, trueLength) * 2) - 1;
    for (int textEnd = trueLength - 1; textEnd < end; textEnd--) {
        if (input[textEnd] == ' ') {
            input[end--] = '0';
            input[end--] = '2';
            input[end--] = '%';
        } else {
            input[end--] = input[textEnd];
        }
    }
}

Code Snippets

void replaceSpaces(char[] input, int trueLength) { ... }
void replaceSpaces(char[] input, int trueLength) {
    //int end = input.length - 1;
    int end = trueLength + (countSpaces(input, trueLength) * 2) - 1;
    for (int textEnd = trueLength - 1; textEnd < end; textEnd--) {
        if (input[textEnd] == ' ') {
            input[end--] = '0';
            input[end--] = '2';
            input[end--] = '%';
        } else {
            input[end--] = input[textEnd];
        }
    }
}

Context

StackExchange Code Review Q#121971, answer score: 9

Revisions (0)

No revisions yet.