Monday, December 8, 2014

Replacing all spaces in a string with '%20'. [Coding Question][Java]

Q. 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.

EXAMPLE

Input:    "Mr John Smith    ", 13
Output:   "Mr%20John%20Smith"

 Source:

public class Code {
    
    //Required Function
    public static String replace(char[] s, int length){
        int spaces = (s.length - length)/2;
        int offset = spaces * 2;
        
        int i=length-1;
        int j=i+offset;
        
        while(i>=0){
            for(;i>=0 && s[i]!=' ';i--, j--)
                s[j] = s[i];
           
            if(j>=2){
                s[j--] = '0';s[j--] = '2';s[j--] = '%';
            } 
            i--;
        }
        return new String(s);
    }
    
    public static void problemTester(String s){
        char a[] = s.toCharArray();
        int blanks = 0;
        for(char c:a)if(c==' ')blanks++;
        char b[] = new char[a.length+2*blanks];  
        
        for(int i=0;i<a.length;++i)b[i]=a[i]; 
        
        System.out.println(replace(b, a.length));
    }
    
    public static void main(String[] args){
        String s = "A string! WOW! "; 
        problemTester(s);
        s = " another string! ";
        problemTester(s);
        s = "one  more!";
        problemTester(s);
        s = " ";
        problemTester(s);
    }
}

Output:

A%20string!%20WOW!%20
%20another%20string!%20
one%20%20more!
%20

No comments:

Post a Comment