0

I created this function that is supposed to replace all the white space within a string with the string "%20". ie: "Mr John Smith" becomes "Mr%20John%20Smith". To accomplish this, I placed all the characters of the string into an array and attempted to loop through, replacing any instance of " " with "%20". For some reason, the code I wrote doesn't seem to recognize the " " value within the list and skips over this part of my loop. So instead of getting a new String with the white spaces replaced, I simply get back the same string with the white spaces intact. Can anyone help correct my error? I ran it through the Java Tutor to visualize my code and it reflected this same error

import java.util.ArrayList;

public class Interview {

    public static void main(String[] args) {

        Interview theFunc = new Interview();

        String d = "Mr John Smith   ";

        System.out.print(theFunc.URLify(d, 13));

    }
    public String URLify(String str, int x){
        String result = "";
        String real = str.substring(0,x);
        String [] list = new String[real.length()];
        int i = 0;
        while (i != real.length()) {
            list[i] = real.substring(i,i+1);
            i = i +1;   
        }
        int b = 0;
        while (b < list.length) {
            if (list[b] == " ") {
                list[b] = "%20";
                b = b + 1;
            }else{
                b = b + 1;
            }
        }
        int d = 0;
        while (d != list.length) {
            result = result + list[d];
            d =d + 1;
        }

    return result;
}

The error is occurring in the second while loop. Thanks!

Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
njfy410
  • 139
  • 12

0 Answers0