Replace a space in a string with%20

Source: Internet
Author: User

This substitution issue is to consider whether the original string will be overwritten if it is replaced directly on the source string.

Seeing this problem, I think a lot of people would think of replacing it directly from the beginning, that is, when you encounter a space, replace it with%20, and each time the character after the space is shifted by two bytes. The time complexity of this solution is O (n^2) ...

Another good solution is to replace from the back, the concrete way is to calculate all the space from the beginning of the calculation of the total length. The precondition of this solution is that if the source string is replaced, the source string will have enough space to accommodate the new string. Time Complexity of O (n) ...

void Replaceblank (char *string, int length) {if (string = = NULL | | length <= 0) {
    return;
    } int originallength = 0;
    int numberofblank = 0;
    int i = 0;
        while (string[i]! = ' + ') {originallength++;
        if (string[i] = = ") {numberofblank++;
    } ++i;
    } int newlength = Originallength + Numberofblank * 2;
    if (Newlength > Length) {return;
    } int indexoforiginal = Originallength;

    int indexofnew = Newlength; 
        while (indexoforiginal >= 0 && indexofnew > Indexoforiginal) {if (string[indexoforiginal] = = ")
            {string[indexofnew--] = ' 0 ';
            string[indexofnew--] = ' 2 ';
        string[indexofnew--] = '% ';
        } else {string[indexofnew--] = string[indexoforiginal];
    }--indexoforiginal; }
}

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.