【Java】编写一个方法,将字符串中的空格全部替换为“ ”

来源:互联网 发布:mac os x最新版本好吗 编辑:程序博客网 时间:2024/04/29 06:42

编写一个方法,将字符串中的空格全部替换为“%20”,假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的真实长度。

因为java里字符串是不可变的,所以如果用java,用字符数组而不是字符串

从后往前放不用担心数据覆盖问题

<span style="font-family:Microsoft YaHei;">public class replaceSpaces {public void spacesReplace(char[] str, int length){int spaceCount = 0, newLength;for( int i = 0; i < length; i++){if (str[i] == ' ')spaceCount++;}newLength = length + spaceCount*2;str[newLength] = '\0';for(int i = length -1; i >= 0; i--){if(str[i] == ' '){str[newLength - 1] = '0';str[newLength - 2] = '2';str[newLength - 3] = '%';newLength = newLength - 3;}else{str[newLength - 1] = str[i];newLength = newLength - 1;}}}}</span>

测试用例:

1. 输入的字符串包含空格(空格位于字符串的最前面,最后面,中间,连续多个空格)

2. 输入的字符串没有空格

3. 特殊输入测试(字符串是null,字符串是空字符串,字符串只有一个空格,字符串只有连续多个空格)


举一反三:

有两个排序的数组A1和A2,在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中的所有数字插入到A1中并且所有数字是排序的。

还是从后往前插入,需要注意的是如果A1的元素比A2的少,比较完成后A2还有一部分元素需要依次插入A1

#include<iostream>using namespace std;void insertString(char A1[], char A2[], int length1, int length2) {if (A1 == NULL || A2 == NULL || length1 < 0 || length2 < 0) {return;}int newlength = length1 + length2;int index1 = length1 - 1;int index2 = length2 - 1;while(index1 >=0 && index2 >= 0) {if (A1[index1] > A2[index2]) {A1[newlength - 1] = A1[index1];index1--;newlength--;}else if (A1[index1] < A2[index2]) {A1[newlength - 1] = A2[index2];index2--;newlength--;}else {A1[newlength - 1] = A2[index2];A1[newlength - 2] = A1[index1];index1--;index2--;newlength -= 2;}}if(length1 < length2) {for( int i = index2; i >= 0; i--) {A1[newlength - 1] = A2[index2];}}}




0 0