Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created April 18, 2012 13:21
Show Gist options
  • Save zac-xin/2413516 to your computer and use it in GitHub Desktop.
Save zac-xin/2413516 to your computer and use it in GitHub Desktop.
1.5 Write a method to replace all spaces in a string with ‘%20’
public class ReplaceSpace {
public static void main(String args[]){
System.out.println(replaceSpace("this is a demo test! "));
}
public static String replaceSpace(String input){
char s[] = input.toCharArray();
int spaceCount = 0;
int index = 0;
for(int i = 0; i < s.length; i++)
if(s[i] == ' ')
spaceCount++;
int newLength = s.length + 2 * spaceCount;
char r[] = new char[newLength];
for(int i = 0 ; i < s.length; i++){
if(s[i] != ' ')
r[index++] = s[i];
else{
r[index++] = '%';
r[index++] = '2';
r[index++] = '0';
}
}
String result = new String(r);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment