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.
packagecrack.coding.interview;
/**
* This class is used to replace all the spaces by "%20" in a string.
* @author rajesh.dixit
*/
public classReplaceSpacesInString {
/**
* Replace spaces from String from "%20"
* @param str
* @return
*/
private staticString replaceSpaces(String str) {
if(str==null) {
return null;
}
int len = str.length();
int count = 0;
/* Count all the spaces in the String. */
for(inti=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(inti=0;i<len;i++) {
char ch = str.charAt(i);
if(' ' == ch) {
newCharArray[j++] = '%';
newCharArray[j++] = '2';
newCharArray[j++] = '0';
} else {
newCharArray[j++] = ch;
}
}
return newString(newCharArray);
}
/**
* Driver Method
* @param args
*/
public static voidmain(String[] args) {
String str = "replace space from string";
String newStr = replaceSpaces(str);
System.out.println(newStr);
}
}
No comments:
Post a Comment