替换空格
替换空格
题目链接
题目描述
将一个字符串中的空格替换成 "%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();
}
}