Skip to content

Instantly share code, notes, and snippets.

@atlas1017
Created June 15, 2014 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atlas1017/d45f5885a83bbfefb800 to your computer and use it in GitHub Desktop.
Save atlas1017/d45f5885a83bbfefb800 to your computer and use it in GitHub Desktop.
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;
}
}
@zhaomizhi
Copy link

Hi, I think there is an error in line 30. It should be j +=3 instead of j+=2.

@jyuan
Copy link

jyuan commented Jun 25, 2014

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