8

I have a question that what does str[newLength] = '\0' mean? because I think the last character should be str[newLength-1], so I don't know the meaning of this line.

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 replaseSpaces(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);
}
Cindy
  • 119
  • 1
  • 1
  • 7
  • Don't do that... You should be using `UrlEncoder` to [encode string for url](http://stackoverflow.com/questions/10786042/java-url-encoding). – Alexei Levenkov Oct 25 '14 at 02:26
  • Doesn't UrlEncoder convert space to plus? – Marichyasana Oct 25 '14 at 02:33
  • 2
    That statement will store a "null" character in the `str` array, at the element indexed by `newLength`. This is effectively null-terminating the C-style string contained in the `str` array. What this means is up to the person who wrote the code -- it's not a standard Java idiom. – Hot Licks Oct 25 '14 at 02:34

3 Answers3

22

The standard library of the C programming language commonly uses NUL-terminated strings. A NUL-terminated string is stored in an array, and the string itself consists of all the characters in an array prior to the first '\0' character (called a NUL in ASCII). For example, if the elements of a character array are {'H','e','l','l','o','\0','i','d','1','0','t'}, the string is "Hello", with everything after the NUL ignored. If you write '\0' to position n of a NUL-terminated string, you will cut off everything after the first n characters, which reduces the string's length to no more than n. The writes to str[newLength - 1] and the like write characters just before the NUL.

I notice you're using the Java programming language, and you're probably trying to translate C code from your book literally to Java. Unlike C, Java doesn't usually use NUL-terminated strings, except in advanced things like JNI where Java code has to talk to C code. Also unlike C, you usually don't have to modify things in place but can instead freely create new copies, as Java has automatic garbage collection to get rid of objects and arrays that your code is no longer using.

Java more often uses the StringBuilder class to construct a string before making an immutable String out of it. So an idiomatic Java solution would create an empty StringBuilder, loop through the characters in an existing String, append("%20") for each character that is a space or append the same character otherwise, and finally convert the StringBuilder instance to a String.

Community
  • 1
  • 1
Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64
6

Java is not C nor C++; Java doesn't use the '\0' character to indicate the end of string ('end of char array' actually in C and C++). Java keeps a 'length' field for arrays so it can do bound checking behind the scenes.

wittakarn
  • 3,124
  • 1
  • 18
  • 31
0
public class StringURLify {

    public static void URLify(String s) {
        char[] c = s.toCharArray();
        int length = s.length();
        int spaceCount = 0, newLength = 0;
        for(int i=0;i<= c.length-1;i++) {
            if(c[i] == ' ') {
                spaceCount++;
            }
        }

        newLength = length + (spaceCount * 2);
        char[] c1 = new char[newLength];

        for(int i=length-1;i>=0;i--) {
            if(c[i] == ' ') {
                c1[newLength - 1] = '0';
                c1[newLength - 2] = '2';
                c1[newLength - 3] = '%';
                newLength = newLength-3;
            } else {
                c1[newLength-1] = c[i];
                newLength = newLength-1;
            }
        }


        System.out.println("URLified string : " + String.valueOf(c1));
    }

    public static void main(String[] args) {
        URLify("the dog left");
    }
}
crusy
  • 1,424
  • 2
  • 25
  • 54