Quick actions

cmd+k|ctrl+k

Navigation

Languages

replace all spaces in a string with '%20'

Snippet info

Language

Java

Visibility

public

Author

arshi.mustafa

Created

2020-10-09T16:43:40Z

Updated

2020-10-09T16:43:40Z

//Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end 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.)

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String str =s.nextLine();
        Main m = new Main();
        int length = str.length();
        String result =m.urlify(str.trim().toCharArray(),length);
        System.out.println(result);
    }
    
    
    public String urlify(char[] a,int length){
        char[] result = new char[length];
        int res_size = 0;
        for(int i=0;i<a.length;i++){
            if(a[i] == ' '){
                result[res_size] = '%';
                result[res_size+1] = '2';
                result[res_size+2] = '0';
                res_size+=3;
            }else{
                result[res_size]= a[i];
                res_size+=1;
            }
            
        }
        return new String(result);
    }
}
INFO