Created
June 17, 2014 11:32
-
-
Save chouclee/d111abfd1ff20e41cd01 to your computer and use it in GitHub Desktop.
[CC150][1.4] Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in pla…
This file contains hidden or 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 replace { | |
public static String replaceBlank (String s) { | |
if(s == null) return null; | |
int count = 0; | |
for (int i = 0; i < s.length(); i++) | |
if (s.charAt(i) == ' ') count++; | |
char[] newStr = new char[s.length() + count << 1]; | |
for (int i = 0 , j = 0; i < s.length() ; i++) { | |
if (s.charAt(i) == ' ') { | |
newStr[j++] = '%'; | |
newStr[j++] = '2'; | |
newStr[j++] = '0'; | |
} | |
else newStr[j++] = s.charAt(i); | |
} | |
return new String(newStr); | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
System.out.println(replace.replaceBlank(" ")); | |
System.out.println(replace.replaceBlank("This is Harold Finch")); | |
System.out.println(replace.replaceBlank("Call me John")); | |
System.out.println(replace.replaceBlank("Haha ha")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment