zoukankan      html  css  js  c++  java
  • Cracking the coding interview--Q1.4

    原文

    Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional
    characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation
    in place.)
    EXAMPLE
    Input: "Mr John Smith        "
    Output: "Mr%20Dohn%20Smith"

    译文:

    写一个函数,把字符串中所有的空格替换为%20 ,并且原字符串末尾的空格要忽略。

    解答

    直接用了java.lang.String里的replaceAll方法,但是为了忽略末尾的空格,先做一些处理,将末尾的空格先修改成一个不可见的其他字符,ASCII小于20的都行。然后替换之后就用trim方法就能去除掉最后的不可见字符。

    public class Main {
    
        public static String replaceSpaces (String str) {
            int len = str.length();
            char a[] = str.toCharArray();
            for(int i = len - 1; i >= 0; i--) {
                if(a[i] == ' '){
                    a[i] = 0;
                }
                else
                    break;
            }
            String str2 = new String(a);
            return str2.replaceAll(" ", "%20").trim();
        }
            
        public static void main(String args[]) {
            String s1 = "Mr John Smith    ";
            System.out.println(replaceSpaces(s1));
        }
    }

    但是如果原字符串首包含ASCII小于20的不可见字符的话就有BUG了。所以又改进了一个版本:

    public class Main {
    
        public static String replaceSpaces (String str) {
            int len = str.length();
            boolean flag = true;
            StringBuilder sb = new StringBuilder();
            for(int i = len - 1; i >= 0; i--) {
                if(str.charAt(i) == ' ' && flag){
                    continue;
                }
                else if(str.charAt(i) == ' ' && !flag) {
                    sb.insert(0, "%20");
                }
                else {
                    sb.insert(0, str.charAt(i));
                    flag = false;
                }
            }
            return sb.toString();
        }
            
        public static void main(String args[]) {
            String s1 = "Mr John Smith    ";
            System.out.println(replaceSpaces(s1));
        }
    }
  • 相关阅读:
    新年新气象~
    北京不下雪,自己来点雪花看看吧~(附效果图)
    没事写个游戏自己玩~
    原生js实现简单的焦点图效果
    php xdebug扩展无法进入断点问题
    (转)没有IE就没有伤害!浏览器兼容性问题解决方案汇总
    利用mvc filterconfig属性实现权限验证
    c# 替换所有中文、标点符号,全角转半角
    go web 第三天 学习笔记 --mysql
    go web 第二天 学习笔记之文件上传
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186164.html
Copyright © 2011-2022 走看看