题解 | #替换空格#

替换空格

http://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68

package JZoffer;

public class JZ2 {

    public String replaceSpace (String s) {
        // write code here

        if (s == null || s.length() == 0){
            return "";
        }

        if (s.length() == 1 && s.equals(" ")){
            return "%20";
        }

        String[] fields = s.split(" ");
        StringBuilder sb = new StringBuilder();


        if (fields.length == 0){

            for (int i = 0; i < s.length(); i++) {

                sb.append("%20");
            }
        }else {

            for (int i = 0; i < fields.length - 1; i++) {

                sb.append(fields[i] + "%20");
            }

            sb.append(fields[fields.length-1]);
            if (s.charAt(s.length()-1) == ' '){
                sb.append("%20");
            }
        }

        return sb.toString();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务