美文网首页
【剑指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】替换空格

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

  • 剑指Offer.C++.code1-5

    剑指offer 代码实现 C++剑指Offer 1. 二维数组中的查找 2. 替换空格 3. 从尾到头打印链表 4...

  • [剑指offer] 替换空格

    本文首发于我的个人博客:尾尾部落 题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符...

  • 剑指offer - 替换空格

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

  • 《剑指offer》替换空格

    问题: 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换...

  • 剑指offer:替换空格

    题目分析 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替...

  • 剑指offer 替换空格

    题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替...

  • [剑指Offer]替换空格

    本文首发于我的个人博客Suixin’s Blog原文: https://suixinblog.cn/2019/02...

  • 【剑指offer】- 替换空格

    1、题目描述 请实现一个函数,把字符串中的每个空格替换成"%20"。 你可以假定输入字符串的长度最大是1000。注...

  • 剑指 offer ---替换空格

    题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经...

网友评论

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

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