请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成

来源:互联网 发布:mac jenkins搭建 编辑:程序博客网 时间:2024/05/07 08:57

请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string。
测试样例:
“Mr John Smith”,13
返回:”Mr%20John%20Smith”
”Hello World”,12
返回:”Hello%20%20World”

package Question1_4;import CtCILibrary.AssortedMethods;public class Question {    // Assume string has sufficient free space at the end    public static void replaceSpaces(char[] str, int length) {        int spaceCount = 0, index, i = 0;        for (i = 0; i < length; i++) {            if (str[i] == ' ') {                spaceCount++;            }        }        index = length + spaceCount * 2;        str[index] = '\0';        for (i = length - 1; i >= 0; i--) {            if (str[i] == ' ') {                str[index - 1] = '0';                str[index - 2] = '2';                str[index - 3] = '%';                index = index - 3;            } else {                str[index - 1] = str[i];                index--;            }        }    }    public static void main(String[] args) {        String str = "abc d e f";        char[] arr = new char[str.length() + 3 * 2 + 1];        for (int i = 0; i < str.length(); i++) {            arr[i] = str.charAt(i);        }        replaceSpaces(arr, str.length());           System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\"");    }}
0 0