美文网首页
【剑指Offer 4】替换空格

【剑指Offer 4】替换空格

作者: 3e1094b2ef7b | 来源:发表于2017-07-02 07:23 被阅读6次

    题目:请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.”。

    Java代码如下:

    package demo;
    
    public class TestString {
        public static int replaceBlank(char[] str, int usedLength) {
            if(str == null || str.length < usedLength) {
                return -1;
            }
            int blankNum = 0;
            for(int i = 0; i < usedLength; i++) {
                if(str[i] == ' ') {
                    blankNum++;
                }
            }
            if(blankNum == 0) {
                return usedLength;
            }
            int targetLength = usedLength + blankNum * 2;
            int tmp = targetLength;
            if(targetLength > str.length) {
                return -1;
            }
            usedLength--;
            targetLength--;
            while(usedLength >= 0 && usedLength < targetLength) {
                if(str[usedLength] == ' ') {
                    str[targetLength--] = '0';
                    str[targetLength--] = '2';
                    str[targetLength--] = '%';
                } else {
                    str[targetLength--] = str[usedLength];
                }
                usedLength--;
            }
            return tmp;
        }
    
        public static void main(String[] args) {
            char[] str = new char[50];
            str[0] = ' ';
            str[1] = 'h';
            str[2] = 'e';
            str[3] = ' ';
            str[4] = 'l';
            str[5] = 'l';
            str[6] = 'o';
            str[7] = ' ';
            str[8] = ' ';
            str[9] = 'w';
            str[10] = 'o';
            str[11] = 'r';
            str[12] = 'l';
            str[13] = 'd';
            str[14] = ' ';
            str[15] = ' ';
            int targetLength = replaceBlank(str, 16);
            System.out.println(new String(str, 0, targetLength));
        }
    }
    
    运行结果

    来源:http://blog.csdn.net/derrantcm/article/details/45330797

    相关文章

      网友评论

          本文标题:【剑指Offer 4】替换空格

          本文链接:https://www.haomeiwen.com/subject/utkncxtx.html