Wednesday 3 February 2016

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


Algorithm:
1. Count the number of spaces during the first scan of the string.
2. Scan the string from start to end for each character:
If a space is encountered, store “%20”.
Else, store the character as it is in the newly shifted location.

package crack.coding.interview;

/**
 * This class is used to replace all the spaces by "%20" in a string.
 * @author rajesh.dixit
 */
public class ReplaceSpacesInString {
    
    
     /**
      * Replace spaces from String from "%20"
      * @param str
      * @return
      */
     private static String replaceSpaces(String str) {
           if(str==null) {
                return null;
           }
          
           int len = str.length();
           int count = 0;
          
           /* Count all the spaces in the String. */
           for(int i=0;i<len;i++) {
                if(str.charAt(i) == ' ') {
                     count ++;
                }
           }
          
           /* Calculate the length of new String and define the new Char array. */
           int newLen = len + 2 * count;
           char[] newCharArray = new char[newLen];
           int j = 0;
          
           for(int i=0;i<len;i++) {
                char ch = str.charAt(i);
                if(' ' == ch) {
                     newCharArray[j++] = '%';
                     newCharArray[j++] = '2';
                     newCharArray[j++] = '0';
                } else {
                     newCharArray[j++] = ch;
                }
           }
           return new String(newCharArray);
     }
    
     /**
      * Driver Method
      * @param args
      */
     public static void main(String[] args) {
           String str = "replace space from string";
           String newStr = replaceSpaces(str);
           System.out.println(newStr);
     }
}



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...