4

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

I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.

public String replace(String str){

   String[] words = str.split(" ");
   StringBuffer sentence = new StringBuffer();

   for(String w: words){
      sentence.append("%20");
      sentence.append(w);
   }

  return sentence.toString();
}
Opal
  • 471
  • 1
  • 7
  • 20
  • 2
    Varies as in it gives the wrong result? Or varies as in this is a correct answer but different from the one in the book? – arynaq Dec 14 '14 at 23:26
  • This should have just worked, please specify how it didn't work, `replaceAll(" ", "%20");` will replace all single space to `%20` but if you are doing it to encode URL take a look at URLEncoder – jmj Dec 14 '14 at 23:27
  • 1
    `sentence = sentence.replace(" ", "%20");`? – fge Dec 14 '14 at 23:28
  • @arynaq In that it is not the answer from the book (and incorrect) and the book answer is way more complicated: http://stackoverflow.com/questions/10007631/write-a-method-to-replace-all-spaces-in-a-string-with-20 – Opal Dec 14 '14 at 23:28
  • 1
    Your sentence will start with "%20". – Tilman Hausherr Dec 14 '14 at 23:28
  • Well, `"a b"` would be `"%20a%20b"`, I wonder why is that not correct? Mhhh ... – Tom Dec 14 '14 at 23:28
  • @Tom because the sentence starts with a "%20" – Opal Dec 14 '14 at 23:30
  • @JigarJoshi I don't think that OP can use existing methods if he should implement that himself. – Tom Dec 14 '14 at 23:30
  • @Opal So you already know, why your answer is wrong? Then what is the purpose of this question? Btw: you should train your sarcasm detector. – Tom Dec 14 '14 at 23:31
  • Strange interview question. The correct answer in most cases would be to construct a `URI`, which does this conversion automaticaly. – user207421 Dec 14 '14 at 23:32
  • I found out why because @TilmanHausherr clarified for me. – Opal Dec 14 '14 at 23:33
  • Oh ok. It sounded like you already knew that. – Tom Dec 14 '14 at 23:34

7 Answers7

6

Question in the book says:

Note: if implementing in Java, please use a character array so that you can perform this operation in place.

It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").

MD-11
  • 911
  • 1
  • 12
  • 25
5

In this loop, the program adds %20 before each word:

   for(String w: words){
      sentence.append("%20");
      sentence.append(w);
   }

That will produce incorrect results, for example for a b it will give %20a%20b.

There's a much simpler solution:

public String replace(String str) {
    return str.replaceAll(" ", "%20");
}

Or, if you really don't want to use .replaceAll, then write like this:

public String replace(String str) {
    String[] words = str.split(" ");
    StringBuilder sentence = new StringBuilder(words[0]);

    for (int i = 1; i < words.length; ++i) {
        sentence.append("%20");
        sentence.append(words[i]);
    }

    return sentence.toString();
}
janos
  • 120,954
  • 29
  • 226
  • 236
  • Maybe a bit late but using `str.replace` is preferred over `replaceAll` as the latter one compiles the regex pattern and then matches and that is why it is slower and not preferred for simple substitutions like whitespace. – subhanceo Oct 30 '22 at 21:58
1

You can also do the following, which replaces any space

String s = "Hello this is a       string!";
System.out.println(replaceSpace(s, "%20"));


public static String replaceSpace(String s, String replacement) {
    String ret = s.replaceAll("  *", replacement);
    return ret;
}

Gives

Hello%20this%20is%20a%20string!
arynaq
  • 6,710
  • 9
  • 44
  • 74
1

One of the simplest way:

public void replaceAll( String str )
{
    String temp = str.trim();

    char[] arr = temp.toCharArray();
    StringBuffer sb = new StringBuffer();

    for( int i = 0; i < arr.length; i++ )
    {
        if( arr[i] == ' ' )
        {
            sb.append( "%20" );
        }
        else
        {
            sb.append( arr[i] );
        }
    }
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
imvp
  • 123
  • 1
  • 11
0
private static String applyReplaceOperationWithCount(String str) {
    if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
        return str;
    }
    char[] strChar = str.toCharArray(); 

    int count = 0; //count spaces in the string to recalculate the array length
    for (char c : strChar) {
        if (c == ' ') {
            count++;
        }
    }

    if (count == 0) { // if there are no spaces in the string, return it 
        return str;
    }

    int length = strChar.length;
    char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
    int index = 0;
    for (char c : strChar) { 
        if (c != ' ') { // if char is not a space just push it in the next available location
            newChar[index++] = c;
        } else { // if char is a space just push %,2,0 
            newChar[index++] = '%';
            newChar[index++] = '2';
            newChar[index++] = '0';
        }
    }
    return new String(newChar); // convert the new array into string
}
user3743369
  • 61
  • 1
  • 4
  • Answers should always come with a bit of explanation, so if you could add that, it would be great! Thank you! – AT82 Jan 11 '17 at 13:41
0

I am using matches and replaceAll it works well.

public class ReplaceSpaces {

public static void main(String[] args) {

    String text = " Abcd olmp  thv ";

    if(text.matches(".*\\s+.*")){
        System.out.println("Yes I see white space and I am replacing it");
        String newText = text.replaceAll("\\s+", "%20");
        System.out.println(newText);
    }
    else{
        System.out.println("Nope I dont see white spaces");
    }
}
}

Output Yes I see white space and I am replacing it %20Abcd%20olmp%20thv%20

Box
  • 113
  • 12
0
public static String replaceSpaceInString(String string,String toreplace){
    String replacedString = "";
    if(string.isEmpty()) return string;
    string = string.trim();
    if(string.indexOf(" ") == -1)return string;
    else{
        replacedString = string.replaceAll("\\s+",toreplace);
    }
    return replacedString;
}
NANCY
  • 61
  • 7