将一个字符串中的空格替换为“ ”(java)

设计一种方法,将一个字符串中的所有空格替换成 %20 。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。

你的程序还需要返回被替换后的字符串的长度。

//将一个字符串中的空格替换为"%20"
import java.util.*;
public class Solution {
    /**
     * @param string: An array of Char
     * @param length: The true length of the string
     * @return: The true length of new string
     */
    public static int replaceBlank(char[] string, int length) {
        int num=0;//konggeshu
        int i=0;
        while(i<length){
            if(string[i]==' '){
                num++;
            }
            i++;
        }
        int newnum=length+2*num;
        char []ch2=new char[newnum];
        int j=0;
        for(i=0;i<length;i++){
            if(string[i]!=' '){
                ch2[j++]=string[i];
            }else{
                ch2[j++]='%';
                ch2[j++]='2';
                ch2[j++]='0';
            }
        }
        /*
        string=Arrays.copyOf(string,length+2*num);
        i=0;
        while(i<length+2*num){
            string[i]=ch2[i];
            i++;
        }
        */
        int t=0;
        while(t<newnum){
            string[t]=ch2[t];
            t++;
        }
       // System.out.println(string);
        return length+2*num;
    }
    public static void main(String []args){
        String str="hello world";
        char []ch=new char[100];
        char []ch1=str.toCharArray();//toCharArray()函数会返回一个新的数组,
                                    //因此就算原数组定义了长度,返回的新数组会取代它
        int i=0;
        while(i<ch1.length){
            ch[i]=ch1[i];
            i++;
        }
        int k=replaceBlank(ch,ch1.length);
        System.out.println(k);
        System.out.println(ch);
    }
}

注:

1、string=Arrays.copyOf(string,length+2*num);

该函数将原来的数组内容复制到一个新分配的数值组中,虽然还是原来的数组引用,但该引用所指向的已经是一个新的数组了。之后对string进行改变,原来的数组并不会改变。

2、char []ch=new char[100];
      char []ch1=str.toCharArray();

toCharArray()函数会返回一个新的数组,因此就算原数组定义了长度,返回的新数组会取代它


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值