Thursday, August 29, 2013

1.4-------Replace space in char[]

Q:
Write a method to replace all spaces in a string with'%20'. You may assume that
the string has sufficient space at the end of the string to hold the additional
characters, and that you are given the "true" length of the string. (Note: if imple-menting in Java, please use a character array so that you can perform this opera-tion in place.)
EXAMPLE
Input: "Mr John Smith"
Output: "Mr%20Dohn%20Smith"


A:

static void replaceSpace(char[] ch, int n){

    // n is the number that actually saved in str

   

    //scan to count the number of space

    int numSpace = 0;

    for(int i = 0 ; i<n; i++){

        if(ch[i]==' ')numSpace++;

    }

    //reversely replace the tokens

    int numSpaceUnreplaced = numSpace;

    for (int i = n-1; i >= 0;i-- ){

        if(ch[i] != ' '){

            ch[i+2*numSpaceUnreplaced] = ch[i];

        }

        else{

            ch[i+2*numSpaceUnreplaced-2] = '%';

            ch[i+2*numSpaceUnreplaced-1] = '2';

            ch[i+2*numSpaceUnreplaced]   = '0';

            numSpaceUnreplaced--;

        }

    }

    System.out.println(ch);

}
Mistake:
1: 竟然不知道怎么声明 char 数组,  哎, 最后只能用String.toCharArray()来声明。
  应该是这样:

  char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd'};

2:








No comments:

Post a Comment