C Language: String substitution spaces: Implement a function that replaces each space in a string with "%20".

Source: Internet
Author: User

Ideas:

In the past: replace on the original basis (of course, if the space is sufficient), if you encounter a space after the trip to replace, it will inevitably overwrite the original character, can not be implemented.

Because the space is replaced with "%20", 2 characters are replaced each time, so you can count the total number of empty cells, and then the new array size is "original array size + space number". Processing from the back: encountered non-whitespace, directly moved to the back, encountered a space replaced by "%20." Until the position pointer is inserted and the original array is the pointer coincident position.

#include <stdio.h> #include <string.h>int main () { char arr[] =  "We are  happy. ";  int i = 0; int j = 0; int len = 0; int  Count = 0; len = strlen (arr);  for (i = 0;i < len;i++)  {  if (arr[i] ==  '   ')   {   count ++;    }   } i = len; j = 2 * count + len;  while (i != j && i >= 0)  {  if (arr[i] ==   '   ')   {   arr[j--] =  ' 0 ';   arr[j--] =  ' 2 ';   arr[j--] =  '% ';   i--;  }  else   {   arr[j] = arr[i];   j--;   i--;   }  } lEn = strlen (arr);  for (i = 0; i< len ;i++)  {  printf ( "%c", Arr[i]);  } printf ("\ n");  return 0; }

650) this.width=650; "title=" capture. PNG "src=" http://s3.51cto.com/wyfs02/M02/75/4F/wKiom1Y1xyzCns4LAACqq2RtT-8746.jpg "alt=" Wkiom1y1xyzcns4laacqq2rtt-8746.jpg "/>

C Language: String substitution spaces: Implement a function that replaces each space in a string with "%20".

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.