Skip to content

Instantly share code, notes, and snippets.

@Jeffwan
Created February 7, 2014 06:06
Show Gist options
  • Select an option

  • Save Jeffwan/8858011 to your computer and use it in GitHub Desktop.

Select an option

Save Jeffwan/8858011 to your computer and use it in GitHub Desktop.
Replace Spaces. Input "Mr John Smith " Output "Mr%20John%Smith". CC150 - Arrays and Strings
package CC150.ArraysAndString;
/**
* 1. Calculate spaces count first, then we know new char[] length
* 2. To prevent overlap, start replace from end to head
*
* true length < str.length because of input may end with many spaces.
* length = str.length - end spaces
*
* book use newLength - 1, then newLength--, I use step here.
*/
public class ReplaceSpaces {
public static void main(String args[]) {
System.out.println(replaceSpaces("Mr John Smith dsadsa ".toCharArray(), 20));
}
public static String replaceSpaces(char[] str, int length) {
int spaceCount = 0;
for (int i=0 ; i< length; i++) {
if (str[i] == ' ') {
spaceCount++;
}
}
int newLength = length + 2 * spaceCount;
str[newLength-1] = '\0'; // always forget here
int step = 2;
for(int i=length-1; i>=0 ; i--) {
if(str[i] != ' ') {
str[newLength-step] = str[i];
step++;
} else {
str[newLength-step] = '0';
str[newLength-step-1] = '2';
str[newLength-step-2] = '%';
step = step + 3;
}
}
return new String(str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment