批量替换字符串

问题描述

在网络编程中,如果URL含有特殊字符,如 空格 、 # 等,服务器将无法识别导致无法获得正确的参数值,我们需要将这些特殊字符转换成服务器可以识别的字符,例如将空格转换成 '%20' 。给定一个字符串,将其中的空格转换成 '%20' 。要求效率尽可能高,尽量在O(n)的复杂度完成,要求用char数组来存储字符,不能用string。

输入格式

一个原始字符串,例如 hello world。

输出格式

输出转换后的字符串,例如 hello%20world。

代码

package javaexam;

import java.util.Scanner;

public class ReplaceStr
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        
        char[] str = input.nextLine().toCharArray(); // 读取一行字符串,存到字符数组里。
        int len = str.length; // len存储字符数组的大小;
        int size = str.length;
        for(int i = 0; i < len; ++i)
        {   // 统计空格字符的个数
            if(str[i] == ' ')
                size += 2; // '%' '2' '0'相对于' ',增加了两个字符空间。
        }
        
        char[] newStr = new char[size];
        for(int i = 0, j = 0; i < len; ++i)
        {
            if(str[i] == ' ')
            {
                newStr[j++] = '%';
                newStr[j++] = '2';
                newStr[j++] = '0';
            }
            else
            {
                newStr[j++] = str[i];
            }
        }
        System.out.println(new String(newStr));
    }
}

样例测试

hello world
hello%20world

猜你喜欢

转载自www.cnblogs.com/narisu/p/9057876.html