Q4:替换空格

来源:互联网 发布:阿里云产品 编辑:程序博客网 时间:2024/06/14 02:34

        替换元素是常见的一类问题。这里给出的例子是替换空格,本题的解题思路有两种方式,推荐大家学习第一种,便于掌握“替换”这一类问题,第二种方法书写简单,但不宜理解。具体问题的分析在代码注释中。

第一种实现方式:

public class Q4 {

   /**

    * 题目:替换空格

    * 题目说明:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.",则输出“We%20are%20happy."

    * 解题思路:如果是循环判断将一个数组复制到另一个数组中,遇到空格就替换,这样开销比较大。最好的方法是,已知原理的字符数目和空格,计算出替换后所需要的空间(现在的空间=原来的空间+2*空格的个数),在原有空间的基础上从后往前进行复制(前提是原有空间足够),遇到空格就替换,直到第一个字符“W”结束。

    */

   public static void main(String[] args) {

      String string = "We are happy.";

      replaceBlack(string);

   } 

   //第一种方法

   public static void replaceBlack(String string){

      //判断字符串是否合法

      if(string ==null){

         return;

      }

      //数组串的实际长度

      int realLength=string.length();

      int numOfBlack = 0;

      //通过循环计算空格的个数

      for(int i = 0; i < string.length(); i++){

         String tempString = String.valueOf(string.charAt(i));

         if(tempString.equals(" ")){

            numOfBlack++;

         }

      }

      //计算替换后的空间大小,即:替换后的字符串的长度

      int newLength = realLength + 2*numOfBlack;

      //开辟一个新的数组空间

      char[] tempChars =newchar[newLength];

      System.arraycopy(string.toCharArray(),0, tempChars, 0, string.length());

      //System.out.println("realLength"+realLength+"\n"+"numOfBlack"+numOfBlack);

     

      //此处将realLength1newLength1作为下标,而不能使用realLengthnewLength作为下标(越界异常)

      int realLength1=realLength-1;

      int newLength1=newLength-1;

      while(realLength1 >=0 && newLength1 !=realLength1){

         //遇到空格进行替换

         if(tempChars[realLength1]==' '){

            tempChars[newLength1--]='0';

            tempChars[newLength1--]='2';

            tempChars[newLength1--]='%';

         }

         else{//非空格情况下将原有字符向后移动即可(此处realLength1不能在--)

            tempChars[newLength1--] =tempChars[realLength1];

         }

         realLength1--;

      }

      System.out.println(tempChars);

   }

}

第二种实现方式:

public class Q4 {

   public static void main(String[] args) {

      String string = "We are happy.";

      System.out.println(replaceBlack(string));

   }  

   public static String replaceBlack(String input){

      if(input ==null){

         return null;

      }

      StringBuffer outputBuffer = new StringBuffer();

      for(int i=0; i<input.length(); i++){

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

            outputBuffer.append("%");

            outputBuffer.append("2");

            outputBuffer.append("0");

         }else {

            outputBuffer.append(String.valueOf(input.charAt(i)));

         }

      }

      return new String(outputBuffer);

   }

}




0 0
原创粉丝点击