Java – write a method to replace all spaces in a string

I have a question about programming, starting with gayl laakmann McDowell's "cracking the code interview" in the fifth edition

The problem is: write a method to replace all spaces in the string with " Assume that the string has enough space at the end of the string to hold other characters, and give the real length of a string I used the book code and a character array to implement the solution in Java (given 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);  
    }
}

The output from my call to replacespaces () is that I am cutting the last character of the original array I've been scratching my head. Anyone can explain to me why the algorithm does this?

Solution

Your length is 6, which leads to this The passage length is 7, including spaces

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

The last character is not considered

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>