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));
        }
    }
  • 相关阅读:
    函数的存储 堆和栈
    函数的容错处理 函数的返回值
    Linux启动故障排查和修复技巧
    干货 | 亿级Web系统负载均衡几种实现方式
    利用expect批量修改Linux服务器密码
    干货 | LVM快照学习
    实战 | Linux根分区扩容
    LVM 逻辑卷学习
    Shell脚本实战:日志关键字监控+自动告警
    手把手教你在Linux中快速检测端口的 3 个小技巧
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186164.html
Copyright © 2011-2022 走看看