Length value when replacing space with% 20

I am working on the problem of replacing spaces with %20from Cracking the Coding Interview 5th edition:

Write a method to replace all spaces in a string with "% 20". You can assume that the line has enough space at the end of the line to hold extra characters and that you are given the "true" length of the line. (Note: if you are implementing in Java, use an array of characters so that you can perform this operation in place)

I have an algorithm:

public static void replaceSpaces(String input, int length) {

    char[] str = input.toCharArray();

    int spaceCount = 0;
    for(int i = length - 1; i >= 0; i--){
        if(str[i] == ' ') {
            spaceCount++;
        }
    }

    int newLength = length + spaceCount * 2;

    str[newLength] = '\0';

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

A listing of each function step, here are my outputs:

Mr John Smith   h
Mr John Smith  th
Mr John Smith ith
Mr John Smithmith
Mr John SmitSmith
Mr John S%20Smith
Mr John n%20Smith
Mr Johnhn%20Smith
Mr Johohn%20Smith
Mr JoJohn%20Smith
Mr%20John%20Smith
Mr%20John%20Smith
Mr%20John%20Smith

I have two questions:

  • , 17. , [newLength - 1] [newLength]. , ? , 17, , 16 (0- ).

  • : str[newLength] = '\0';

+4
4

, , :

"%20". , "" . (: , Java, , )

Cracking the Coding Interview 5-


, , input char[].

, .


1:

, 17. , [newLength - 1] [newLength]. , ? , 17, , 16 (0- ).

. 17 0 16. 17 , 17 IndexOutOfBoundsException.


2:

: str [newLength] = '\ 0';

. Java. .

Java length(). C , Java.


, :

char[] buffer = { 'M','r',' ','J','o','h','n',' ','S','m','i','t','h','*','*','*','*' };
int inLen = 13;
System.out.println("buffer: '" + new String(buffer) + "'");
System.out.println("inLen : " + inLen);
System.out.println("input : '" + new String(buffer, 0, inLen) + "'");
int outLen = replaceSpaces(buffer, inLen);
System.out.println("outLen: " + outLen);
System.out.println("result: '" + new String(buffer, 0, outLen) + "'");

:

buffer: 'Mr John Smith****'
inLen : 13
input : 'Mr John Smith'
outLen: 17
result: 'Mr%20John%20Smith'

input[17] IndexOutOfBoundsException.


, , .

public static int replaceSpaces(char[] str, int length) {
    int spaceCount = 0;
    for (int i = length - 1; i >= 0; i--)
        if (str[i] == ' ')
            spaceCount++;
    int shift = spaceCount * 2;
    int newLength = length + shift;
    for (int i = newLength - 1; shift > 0; i--) {
        char c = str[i - shift];
        if (c != ' ') {
            str[i] = c;
        } else {
            str[i] = '0';
            str[--i] = '2';
            str[--i] = '%';
            shift -= 2;
        }
    }
    return newLength;
}

.

+1

. .

 package StringAndArray;


 public class Question_Four_Replace_Spaces {

 public static void main(String[] args) {
    String string = "Mr Shubham Dilip Yeole";
    char[] array = string.toCharArray();
    System.out.println("\n\nInput : " +string);
    System.out.println("\n\nResult: "+method_1(array,string.length()));
    method_1(array,string.length());
 }


private static String method_1(char[] array, int length) {
    int spaceCount = 0;
    for(int i=0; i<array.length; i++){
        if(array[i]==' ') spaceCount++;
    }
    int count = 0;
    int newLength = length + spaceCount*2;
    char[] newArray = new char[newLength];

    for(int i= 0; i<array.length; i++){
        if(array[i]==' '){
            newArray[count++] = '%';
            newArray[count++] = '2';
            newArray[count++] = '0';
        }else{
            newArray[count] = array[i];
            count++;
        }
    }
    String newString1 = new String(newArray);

    return newString1;
}
}
+1

, , .

, String ( ), . , , , Java , , , , .

, , , %20. String. , Java , , StringBuilder.

, ( ) Java :

public static String replaceSpaces(String input)
{
    if (input == null) return null;

    // New string builder with some padding to account for replacements...
    // Padding was chosen pretty arbitrarily, there are certainly better values.
    StringBuilder builder = new StringBuilder(input.length() + 128);

    for (int i = 0; i < input.length(); i++)
    {
        char c = input.chatAt(i);
        if (c == ' ') {
            builder.append("%20");
        } else {
            builder.append(c);
        }
    }

    return builder.toString();
}

It might be more optimal to convert the entire string to char[]at the beginning and iterate over the array instead of using String.charAt(i). And we could choose a more suitable complement for StringBuilderby multiplying the length of the existing string by some constant based on the expected number of spaces. For very large lines, it may even make sense to first count the number of spaces before declaring our array, but these optimizations remain as an exercise for the reader.

0
source
@Test public void replaceTest() {
    String s = "Mr John Smith      ";
    char[] chars = s.toCharArray();
    int length = 13;
    char[] chars1 = subString(chars, length);
    //actualString = actualString.replace(" ", "%20");
    Assert.assertEquals(replace(chars1, "%20"), "Mr%20John%20Smith");
  }

  private char[] subString(char[] chars, int length) {
    char[] newChar = new char[length];
    for (int i = 0; i < length; i++) {
      newChar[i] = chars[i];
    }

    return newChar;
  }

  private String replace(char[] chars, String s) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < chars.length; i++) {
      if (chars[i] == ' ') {
        builder.append(s);
      } else {
        builder.append(chars[i]);
      }
    }
    return builder.toString();
  }
0
source

Source: https://habr.com/ru/post/1607711/


All Articles