字符串中的空格替换问题(Java版)

Posted liguangsunls

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串中的空格替换问题(Java版)相关的知识,希望对你有一定的参考价值。

技术分享

技术分享

解决方式一:时间复杂度为O(n^2)

技术分享

技术分享

解决方式二:时间复杂度为O(n)

技术分享

技术分享

技术分享
代码实现:

package string;

public class SpaceStringReplace2 {
    //len为数组大小的总容量
    public static void SpaceReplace(String strOld,int len){
        char[] chs =new char[len];
        char[] ch = strOld.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            chs[i] = ch[i];
        }

        int strOldLen = 0;
        int blackString = 0;
        if(chs==null || len<=0)
        {
            new NullPointerException(); 
        }

        int i=0;
        while(chs[i]!=‘\0‘){
            strOldLen++;
            if(chs[i]==‘ ‘){
                blackString++;
            }
            i++;
        }
        //将空格转换成%20字符的长度
        int strNewLen = strOldLen + blackString*2;
        if(strNewLen>len){
            new ArrayIndexOutOfBoundsException();
        }

        int indexOfOld=strOldLen;//指向‘\0‘
        int indexOfNew=strNewLen;

        while(indexOfOld>0 && indexOfNew>indexOfOld){
            if(chs[indexOfOld] == ‘ ‘){
                chs[indexOfNew--] = ‘0‘;
                chs[indexOfNew--] = ‘2‘;
                chs[indexOfNew--] = ‘%‘;
            }
            else{
                chs[indexOfNew--] = chs[indexOfOld];
            }
            --indexOfOld;
        }   
        for (char c : chs) {
            if(c==‘\0‘){
                break;
            }
            System.out.print(c);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        //StringBuilder str = new StringBuilder("We are happy.");
        long timelast = System.currentTimeMillis();
        String str = "We are happy.";
        SpaceReplace(str,100);//We%20are%20happy.

        long timeafter = System.currentTimeMillis();
        System.out.println(timeafter-timelast);
    }
}

解决方式三JDK自带的字符串分割

代码实现:

package string;

public class SpaceStringReplace {
    public static String SpaceReplace(String strOld){
        String[] split = strOld.split(" ");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < split.length-1; i++) {
            stringBuilder.append(split[i]).append("%20");
        }
        stringBuilder.append(split[split.length-1]);
        String strNew = stringBuilder.toString();
        return strNew;
    }

    public static void main(String[] args) {
        //StringBuilder str = new StringBuilder("We are happy.");
        String str = "We are happy.";
        System.out.println(SpaceReplace(str));//We%20are%20happy.
    }
}

以上是关于字符串中的空格替换问题(Java版)的主要内容,如果未能解决你的问题,请参考以下文章

编写一个方法,用 '%20' 替换字符串中的所有空格

剑指 Offer(第 2 版)刷题 | 05. 替换空格

java问题:String字符串替换部分空格,保留特定空格,如何做?

替换空格(基于js)

剑指offer 2.替换空格

leetcode刷题28.替换空格——Java版