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;//12
for(int i=0;i<orginalLength;i++)
{
if(str[i] == ' ')
{
numOfBlank++;
}
}
int newLength=orginalLength+numOfBlank*2;//16-1
if(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 stub
char[] str=new char[]{'w','e',' ','a','r','e',' ','w','o','r','l','d'};//12
char[] newstr=replaceBank(str,100);
display(newstr);
}
}
面试题4:替换空格
最新推荐文章于 2021-11-22 10:56:00 发布