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 place.)
package javaapplication2;
import java.io.*;/**
*
* @author user
*/
public class JavaApplication2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="";
InputStreamReader input= new InputStreamReader(System.in);
BufferedReader reader= new BufferedReader(input);
try {
s1=reader.readLine();
}
catch(IOException e)
{ e.printStackTrace();}
s1=s1.replace(" ", "%20");
char[] a= s1.toCharArray();
System.out.println(s1.length());
System.out.println(s1);
}
}
if we want to use method in place:
package javaapplication2;
import java.io.*;
/**
*
* @author user
*/
public class JavaApplication2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="";
InputStreamReader input= new InputStreamReader(System.in);
BufferedReader reader= new BufferedReader(input);
try {
s1=reader.readLine();
}
catch(IOException e)
{ e.printStackTrace();}
s1=s1.replace(" ", "%20");
int count=0,i=0;
char a[]= s1.toCharArray();
for(i=0;i<a.length;i++)
{
if(a[i]==' ')
count++;
}
for(;i<0;i--)
{
if(a[i]!=' ')
a[i+2*count]=a[i];
else
{
a[i+(2*count)]='0';
a[i+(2*count)-1]='2';
a[i+(2*count)-2]='%';
count--;
}
}
System.out.println(s1.length());
System.out.println(s1);
System.out.println(a.length);
System.out.println(a);
}
}