/** * Sword refers to the offer of the 4th question to replace the space * Features: 1, first scan the number of spaces in the string, calculate the length of the replacement * 2, using a double pointer, starting from behind to replace the forward, to avoid the beginning of each replacement after the previous move all the data * Test Cases: Special: There are multiple spaces * ERROR: String null * */package Javatrain;public class Offer4 {public static void main (string[] args) {string a = "Hello I am Da" Isy dong! "; Replaceblack (a);} public static void Replaceblack (String a) {if (a = = null) return;int len = 0;int count = 0;//The number of spaces char[] str = A.tochararr Ay (); len = str.length;for (char s:str) {if (s = = ") ++count;} Replace with double pointer and move back int p1 = Len-1;len + = count*2;int P2 = len-1;char[] str1 = new Char[len];while (P1 >= 0) {if (STR[P1] = = ') {str1[p2] = ' 0 '; str1[--p2] = ' 2 '; str1[--p2] = '% ';} else {STR1[P2] = Str[p1];} --P2;--P1;} System.out.println (STR1);}}
"Sword means offer" the fourth question replaces the space