Created
June 15, 2014 22:34
-
-
Save atlas1017/d45f5885a83bbfefb800 to your computer and use it in GitHub Desktop.
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 replacechar | |
{ | |
public static void main(String[] args) { | |
String s = "Mr John Smith"; | |
String ms = add(s); | |
System.out.println(s); | |
System.out.println(ms); | |
} | |
public static String add(String s) | |
{ | |
// count num of '' | |
int count = 0; | |
for(int i = 0; i < s.length(); i++) | |
{ | |
if(s.charAt(i) == ' ') | |
count++; | |
} | |
char[] result = new char[s.length() + count*2]; | |
int j = 0; | |
for(int i = 0; i < s.length(); i++) | |
{ | |
if(s.charAt(i) == ' ') | |
{ | |
result[j] = '%'; | |
result[j+1] = '2'; | |
result[j+2] = '0'; | |
j += 2; | |
} | |
else | |
result[j] = s.charAt(i); | |
j++; | |
} | |
String sresult = new String(result); | |
return sresult; | |
} | |
} |
The spaces at the end of the String should be ignored!
What's more, if implements in Java, the input type should be char[] rather than string. Because the Question required perform this operation in place
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I think there is an error in line 30. It should be j +=3 instead of j+=2.