1. 程式人生 > >java實現替換空格

java實現替換空格

題目:當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

    public class Solution {
public String replaceSpace(StringBuffer str) {

           int n = str.length();

          //字串的長度

            int ii = 0;

           //空格的個數ii

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

                //檢測空格

                  if(str.charAt(i)==' '){

                            ii++;

                        } }

                   int nn = 2 * ii + n;

                      //根據空格的個數,得到新陣列的長度

                       int index = nn -1;

                      char[] ct = new char[nn];//新建陣列

                     while(n > 0){

                           if(str.charAt(n - 1) != ' '){

                               //如果不是空格

                                 ct[index--] = str.charAt(n-1);

                                   } else{

                                   //如果是空格

                                   ct[index--] = '0';

                                  ct[index--] = '2';

                                 ct[index--] = '%'; }

                                   //取下一個字元 n--;

                                        }

                                     return String.valueOf(ct);

                                     //將字元陣列轉為String型別後返回

                         } }