面试题4:替换空格

来源:互联网 发布:c语言中struct的用法 编辑:程序博客网 时间:2024/06/05 22:29
public class Demo4 {static char[] replaceBank(char[] str,int length){if(str == null && length<=0){return null;}int numOfBlank=0;int orginalLength=str.length-1;//12for(int i=0;i<orginalLength;i++){if(str[i] == ' '){numOfBlank++;}}int newLength=orginalLength+numOfBlank*2;//16-1if(newLength>length){return null;}char[] temp=new char[newLength+1];System.arraycopy(str, 0, temp, 0, orginalLength);while(orginalLength>0 && newLength>orginalLength){if(str[orginalLength] ==' '){temp[newLength--]='%';temp[newLength--]='2';temp[newLength--]='0';}else{temp[newLength--]=str[orginalLength];}orginalLength--;}return temp;}static void display(char[] str){for(int i=0;i<str.length;i++)System.out.print(str[i]);}public static void main(String[] args) {// TODO Auto-generated method stubchar[] str=new char[]{'w','e',' ','a','r','e',' ','w','o','r','l','d'};//12char[] newstr=replaceBank(str,100);display(newstr);}}

0 0
原创粉丝点击