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));
        }
    }
  • 相关阅读:
    如何安装mysql
    07 登录接口开发
    06 跨域问题
    05 实体校验
    04 异常处理
    03 整合shiro+jwt 会话共享
    02 统一结果封装
    01 新建SpringBoot项目 整合Mybatis Plus(Spring Boot 前后端分离)
    结合Scikit-learn介绍几种常用的特征选择方法
    Set_ML
  • 原文地址:https://www.cnblogs.com/giraffe/p/3186164.html
Copyright © 2011-2022 走看看