替换空格

替换空格

题目链接

https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68?tpId=13&tqId=11155&tab=answerKey&from=cyc_github

题目描述

将一个字符串中的空格替换成 "%20"。

Input:
"A B"

Output:
"A%20B"

package com.huang.datastructure;

/**
 * @Author 黄显超
 * @Date 2022/1/4
 */
public class ReplaceString {
    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("A B");
        String s = replaceString(str);
        System.out.println(s);


        String str1 = "A B";
        String s1 = replaceSpace(str1);
        System.out.println(s1);

    }

    /**
		第一种解法
		
	在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),所以当遍历到一个空格时,需要在尾部填充两个任意字符。

 	P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
 	
     * @param str
     */
    public static String replaceString(StringBuilder str) {
        int p1 = str.length() - 1;
        for (int i = 0; i <= p1; i++) {
            if(str.charAt(i) == ' ') {
                //如果有空格就在后面追加两个空的字符串
                str.append("  ");
            }
        }
        int p2 = str.length() - 1;
        //当 P2 遇到 P1 时(P2 <= P1),或者遍历结束(P1 < 0),退出。
        while (p1 >= 0 && p2 > p1) {
            //从后往前遍历
            char c = str.charAt(p1--);
            if(c == ' ') {
                //遇到一个空格就设置%20
                str.setCharAt(p2--,'0');
                str.setCharAt(p2--,'2');
                str.setCharAt(p2--,'%');
            }else {
                //否则就设置原来的字符
                str.setCharAt(p2--,c);
            }
        }
        return str.toString();
    }

    //第二种解法
    public static String replaceSpace(String s) {
        StringBuilder b = new StringBuilder();
        int length = s.length() - 1;
        for (int i = 0; i <= length; i++) {
            if(s.charAt(i) == ' ') {
                b.append("%20");
            }else {
                b.append(s.charAt(i));
            }
        }
        return b.toString();
    }
}
posted @   China熊孩子  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示