Replace Space with %20

Replace Space with %20

 
Write a method to replace every space within string with %20.
 
example :
 
Input : “Mr John Smith    ”
 
Output : Mr%20John%20Smith
 
Here is the code :
 



public class StringEdit {
static void replaceSpaces(char[] str, int trueLength) {
int spaceCount = 0, index, i = 0;
for (i = 0; i < trueLength; i++) {
if (str[i] == ' ') {
spaceCount++;
}
}
index = trueLength + spaceCount * 2;
if (trueLength < str.length) {
str[trueLength] = '\0';
}
for (i = trueLength - 1; i >= 0; i--)
{
if (str[i] == ' ') {
str[index - 1] = '0';
str[index - 2] = '2';
str[index - 3] = '%';
index = index - 3;
} else {
str[index - 1] = str[i];
index--;
}
}
System.out.println(new String(str));
}
public static void main(String[] args) {
replaceSpaces("Mr John Smith    ".toCharArray(),13);
}
}


 
Output:






No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON