写一个方法用“%20”替换字符串中的所有空格 [英] Write a method to replace all spaces in a string with '%20'

查看:184
本文介绍了写一个方法用“%20”替换字符串中的所有空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于从书开裂Gayl Laakmann麦克道尔,第五版code面试一个规划问题的问题。

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.

问题指出:写一个方法,%20替换字符串中的所有空格。假设字符串有在字符串结尾足够的空间来容纳更多的字符,你接到一个字符串的真实长度。我用书code,使用字符数组(鉴于Java字符串是不可变的)用Java实现的解决方案:

The problem states: Write a method to replace all spaces in a string with '%20'. Assume string has sufficient space at end of string to hold additional characters, and that you're given a true length of a string. I used the books code, implementing the solution in Java using a character array (given the fact that Java Strings are immutable):

public class Test {
    public void replaceSpaces(char[] str, int length) {
        int spaceCount = 0, newLength = 0, i = 0;

        for(i = 0; i < length; i++) {
            if (str[i] == ' ') 
                spaceCount++;
        }

        newLength = length + (spaceCount * 2);
        str[newLength] = '\0';
        for(i = length - 1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[newLength - 1] = '0';
                str[newLength - 2] = '2';
                str[newLength - 3] = '%';
                newLength = newLength - 3;
            }
            else {
                str[newLength - 1] = str[i];
                newLength = newLength - 1;
            }
        }
        System.out.println(str);
    }

    public static void main(String[] args) {
        Test tst = new Test();
        char[] ch = {'t', 'h', 'e', ' ', 'd', 'o', 'g', ' ', ' ', ' ', ' ', ' ', ' '};
        int length = 6;
        tst.replaceSpaces(ch, length);  
    }
}

我从 replaceSpaces得到()调用的输出是:的%20do 这是切原数组的最后一个字符。我一直在抓我的头在这个,为什么算法是这样做的任何人都可以解释一下吗?

The output I am getting from the replaceSpaces() call is: the%20do which is cutting of the last character of the original array. I have been scratching my head over this, can anyone explain to me why the algorithm is doing this?

推荐答案

正在传递长度6,这是造成这一点。通过长度7包括空间。
其他明智

You are passing the length as 6, which is causing this. Pass length as 7 including space. Other wise

for(i = length - 1; i >= 0; i--) {

不会考虑最后一个字符。

will not consider last char.

这篇关于写一个方法用“%20”替换字符串中的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆