Created
April 18, 2012 13:21
-
-
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’
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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