Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How can I replace space with 20 java?

Asked by Nikita Gavde Oct 12, 2022 1.1K views 1 answer
Share

About this question

 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();
    }
}


Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.