剑指offer第二题替换空格 不用replace

来源:互联网 发布:中国工业企业数据库 编辑:程序博客网 时间:2024/06/08 11:58
package fenshujs;


import java.util.Scanner;


public class Janzhioffer {
/*
 * 剑指offer第二题  替换空格
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
       Scanner sc = new Scanner(System.in);
       char[] a = sc.nextLine().toCharArray();
       int count = 0;
       for(int i = 0;i<a.length;i++)
       {
      if(a[i] == 32)
      {
      count++;
      }
       }
       char[] b = new char[a.length+count*2];
       int p2 = b.length-1;
       for(int i = a.length-1;i>=0;i--)
       {
      if(a[i] != 32)
      {
      b[p2] = a[i];
      }
      else
      {
      b[p2] = '0';
      b[--p2] = '2';
      b[--p2] = '%';
      }
      p2--;
       }
       System.out.println(b);
}


}



We Are Happy
We%20Are%20Happy