02. Replace spaces

topic

Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy. The string after replacement is We% 20Are% 20Happy.

Code implementation 1

public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replace(" ", "%20");
    }
}

Code implementation 2

public class Solution {
    public String replaceSpace(StringBuffer str) {
        StringBuffer result = new StringBuffer();
        String target = str.toString();
        for(int i = 0; i < target.length(); i++){
            char c = target.charAt(i);
            if(c == ' '){
                result.append("%20");
            }else{
                result.append(c);
            }
        }
        return result.toString();
    }
}
Published 12 original articles · praised 0 · visits 89

Guess you like

Origin blog.csdn.net/charlotte_tsui/article/details/105320066