<剑指offer 面试题5>替换空格(Java)

来源:互联网 发布:怎么在淘宝上投诉卖家 编辑:程序博客网 时间:2024/06/03 22:56
import java.util.Scanner;public class Interview5 {public static void main(String[] args) {// TODO Auto-generated method stubScanner sc=new Scanner(System.in);String str=sc.nextLine();replaceSpace(str);}/** * 题目描述:请实现一个函数,把字符串中的每个空格替换成"%20"。 * 思路:先判断新的数组需要多少空间,然后从后往前填充 * @param str */public static void replaceSpace(String str){//判断字符串的合法性if(str==null){return ;}//统计空格的数目int count = 0; for(int i=0;i<str.length();i++){String s=String.valueOf(str.charAt(i));if(s.equals(" ")){count++;}}int prelength=str.length();int newlength=prelength+2*count;char copyString[]=new char[newlength];int newlength1=newlength-1;int prelength1=prelength-1;//复制数组到新的数组空间System.arraycopy(str.toCharArray(), 0, copyString, 0, str.length());while(prelength1>=0&&prelength1!=newlength1){if(copyString[prelength1]==' '){copyString[newlength1--]='0';copyString[newlength1--]='2';copyString[newlength1--]='%';}elsecopyString[newlength1--]=copyString[prelength1];prelength1--;}System.out.println(copyString);}}

原创粉丝点击