Implement a function that replaces a space in a string with "%20". For example, when the string is we are Happy. The string after substitution is we%20are%20happy.
Note that the time complexity is O (n), which is replaced by a backward forward.
Public classMain { Public Static voidMain (string[] args) {main Main01=NewMain (); String Str=main01.replacespace (NewStringBuffer ("Old string")); System.out.println (str); } PublicString replacespace (StringBuffer str) {if(str==NULL|| Str.length () <0){ return NULL; } //to find the actual length of the string and the number of spaces intOldstrnum=0,blancknum=0; intI=0; while(i<str.length ()) {Oldstrnum++; if(Str.charat (i) = = ") {Blancknum++; } I++; } intnewstrnum=oldstrnum+2*Blancknum; intOldstrindex =oldstrnum-1, Newstrindex=newstrnum-1; Charnewchararr[]=New Char[Newstrnum]; while(oldstrindex>=0){ if(Str.charat (oldstrindex) = = ") {Newchararr[newstrindex--]= ' 0 '; Newchararr[newstrindex--]= ' 2 '; Newchararr[newstrindex--]= '% '; }Else{Newchararr[newstrindex--]=Str.charat (Oldstrindex); } Oldstrindex--; } String newstr=string.valueof (Newchararr); returnNewstr; }}
Interview 5: Implement a function that replaces a space in a string with "%20". For example, when the string is we are Happy. The string after substitution is we%20are%20happy.