How can I replace space with 20 java?

503    Asked by NikitaGavde in Java , Asked on Oct 12, 2022

 This is not very memory-efficient. Can you please suggest a better way or improvement?

public class Test{
public static void main(String[] args) {
        System.out.println(replaceSpace("All men must die"));
    }
    public static String replaceSpace(String s) {
        String[] stringArray = s.split(" ");
        StringBuffer sb = new StringBuffer();
        for(String s3 : stringArray) {
            sb.append(s3);
            sb.append(" ");
        }
        // if the last character is not space then, don't append .
        if(s.charAt(s.length()-1) != ' ') {
            return sb.substring(0, sb.length()-3).toString();
        }
        return sb.toString();
    }
}


Answered by NISHA arti

Don't replace space with 20 java yourself. Instead use java.net.URLEncoder or another library implementation of url encoding. You'll also get support for other characters as well besides space


Your Answer

Interviews

Parent Categories