Write a method to replace all spaces in the string "% 20"?

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

I'm not sure what's wrong with my answer? It depends on 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();
}
+4
source share
6 answers

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

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

This will lead to incorrect results, for example, for a bhe will give %20a%20b.

There is a much simpler solution:

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

Or, if you really do not want to use .replaceAll, 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();
}
+5
source

The question in the book reads:

. Java , .

, char, , , .
split StringBuffer, O (n). ( "%20").

+6

,

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;
}

Hello%20this%20is%20a%20string!
+1

:

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] );
        }
    }
}
+1
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
}
0

matches replaceAll, .

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");
    }
}
}

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

0

All Articles