public class Solution { public String replaceSpace(StringBuffer str) { String str1=str.toString(); char[] charArray = str1.toCharArray(); StringBuilder sBuilder = new StringBuilder(); for (char c : charArray) { if(c==' ') { sBuilder.append("%20"); }else { sBuilder.append(c); } } String string = sBuilder.toString(); return string; }}
import java.util.Scanner;public class ReplaceSpace { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str=scanner.nextLine(); scanner.close(); char[] charArray = str.toCharArray(); int length=charArray.length; int spaceNumber=0;//获取空格数量 for (char c : charArray) { if(c==' ') { spaceNumber++; } } int newLength=length+spaceNumber*2; char[] tempArray=new char[newLength];//新的数组的长度 System.arraycopy(charArray, 0, tempArray, 0, length);//将原来的数组拷贝到新长度的数组中 int indexofOriginal = length - 1; int indexofNew = newLength - 1; while (indexofOriginal>=0&&indexofOriginal!=indexofNew) { if (tempArray[indexofOriginal]==' ') { tempArray[indexofNew--] = '0'; tempArray[indexofNew--] = '2'; tempArray[indexofNew--] = '%'; }else { tempArray[indexofNew--] = tempArray[indexofOriginal]; } indexofOriginal--; } for (char c : tempArray) { System.out.print(c); } }}