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.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.