Monday, July 17, 2017

Write a method to replace all spaces in a string with ‘%20’


/**
 * Problem: Write a method to replace all spaces in a string with ‘%20’.
 */
public class ReplaceSpaceChar {

    /*
    First count the number of space character, each space character would be replaced by 3 characters (2 addition's)
    so calculate new length by adding no of space chars * 2 to original length. Then start copying characters
    from back and while copying replace each space with %20
     */
    public  void replaceSpaceChar(char[] str, int length) {
        int noOfSpaceChars = 0;
        for(int i = 0;  i < length; i++){
            if(Character.isSpaceChar(str[i])){
                noOfSpaceChars++;
            }
        }
        int newLength = length + (noOfSpaceChars*2);
        int writeIndex = newLength;
        for(int i = length-1; i >=0 ; i--){
            char currentChar = str[i];
            if(!Character.isSpaceChar(currentChar)){
               str[writeIndex--] = currentChar;
            }else{
                str[writeIndex--] = '0';
                str[writeIndex--] = '2';
                str[writeIndex--] = '%';

            }
        }
    }
}

No comments:

Post a Comment