string_Q3

package chapter1;

/*
 * Q:given a string and it's real length,replace blank of string to %20
 *   Assume string has sufficient free space at the end
 * E:input:"Mr John Smith ", 13
     output:"Mr%20John%20Smith"
 * S:Traverse the array from end to start,so replace don't cover exit char
 */
public class Q3 {
    public static  String URLify(String s) {
        char[]s1=s.toCharArray();
        int TrueLength=FindLastCharecter(s1);
        int len=0,space=0;
        for(int i=0;i<TrueLength;i++) {
            if(s1[i]==' ')space++;
        }
        len=TrueLength+2*space;
        //if(TrueLength<s.length())s1[TrueLength]='\0';
        for(int i=TrueLength;i>=0;i--) {
            //char c=s1[i];
            if(s1[i]==' ') {
                
                s1[len--]='0';
                s1[len--]='2';
                s1[len--]='%';
            }
            else {
                s1[len--]=s1[i];
            }
        }
        String str = new String(s1);
        return str;
    }
    public static int FindLastCharecter(char[] s) {
        for(int i=s.length-1;i>=0;i--) {
            if(s[i]!=' ') return i;
        }
        return -1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "Mr John Smith    ";
        char[]s=str.toCharArray();
        System.out.println(FindLastCharecter(s));
        System.out.println(URLify(str));
    }
}

posted @ 2021-04-25 22:36  幻影如梦  阅读(55)  评论(0)    收藏  举报