"Sword Pointing Offer" Java Implementation - Replace Spaces

Topic description

Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

ideas

This topic seems relatively simple, but there are many situations that need to be considered in order to do AC. 1. An empty string
2. A string with only spaces, 3. The case where the last or first character is a space.

code

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int length = str.length();
         if (length == 0)
            return "";
        if (str.charAt(length-1)==' ') {
            str.deleteCharAt(length-1);
            str.append("%20");
        }
        String s = str.toString();
        String strs[] = s.split(" ");
        StringBuffer sb = new StringBuffer();
        for (String temp:
             strs) {
            sb.append(temp);
            sb.append("%20");
        }
        sb.delete(sb.length()-3, sb.length() );
        return sb.toString();
    }

}
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640491&siteId=291194637
Recommended