Alternate spaces in C + +

Source: Internet
Author: User

example, implement a function that replaces each space in a string with "%20". For example, enter "We are happy.", then output "we%20are%20happy."

Analysis:

We can iterate through the string one at a time, so that we can count the total number of empty cells of a string, and thus calculate the total length of the string after substitution. Each time a space is replaced, the length increases by 2, so the length of the string after replacement is equal to the original length plus 2 times the number of spaces. We are still using the preceding string ' We are happy, ' for example, "We are happy '" The length of this string is 14 (including the trailing sign ' + '), which has two spaces, so the length of the string after substitution is 18.

We start by copying and replacing from behind the string. First, prepare two pointers , P1 and P2. P1 points to the end of the original string, and P2 points to the end of the string after substitution (a). Next we move the pointer P1, copying the character it points to the position that P2 points to, until the first space is encountered. At this point the string contains (b) as shown, and the area of the gray background is the area where the character is copied (moved). After encountering the first space, move the PL forward by 1 squares and insert the string "%20" before P2. Since the length of "%20" is 3, it is also necessary to move the P2 forward by 3 grid (c) as shown.

We then copied forward until we hit the second space (shown in 2.4 (d)). As we did last time, we move the P1 forward by 1 and move the P2 forward by 3 cells into "%20" (2.4 (e)).   At this point P1 and P2 point to the same location, indicating that all spaces have been replaced. From the above analysis we can see that all characters are only copied (moved) once, so the time efficiency of the algorithm is O (n), high efficiency.




Note: The shaded area in the figure represents the character being moved .

(a) Point the first pointer at the end of the original string and point the second pointer at the end of the replaced string.

(b) Copy the contents of the string sequentially until the first pointer touches the first space.

(c) Replace the penultimate space with "%20", then move the first pointer forward by 1 squares and move the second pointer 3 squares forward.

(d) The characters in the string are copied forward until a space is encountered.

(e) Replace the second-to-last space in the string, then move the first pointer forward by 1 squares and move the second pointer 3 squares forward.

In the process of the interview, we can also be the same as the previous analysis, draw one or two, explain their own ideas, so that both help us to clarify the idea, but also can make us and the interviewer's communication become more efficient. After the interviewer has affirmed our thinking, we can start writing the code. Here is the reference code:

Length is the total capacity of the character array string void Replaceblank (char str[],int length) {if (str==null && length<=0) return;// Originallength is the actual length of the string str int originallength=0;int numberofblank=0;int i=0;while (str[i]!= ' n ') {++originallength; if (str[i]== ') ++numberofblank;++i;} Newlength the length int newlength=originallength + numberofblank*2;if (newlength>length) Return;int after replacing the space with '%20 ' Indexoforiginal=originallength;int indexofnew=newlength;while (indexoforiginal>=0 && indexOfNew> indexoforiginal) {if (str[indexoforiginal]== ') {str[indexofnew--]= ' 0 '; str[indexofnew--]= ' 2 '; str[indexofnew--]= '% ';} Else{str[indexofnew--]=str[indexoforiginal];} --indexoforiginal;}}

Test Case:

1) in the input stringinclude spaces(Spaces are in the stringthe front, the space is in the string'sLast Face, the space is in the string'sMiddle, the string hasmultiple consecutiveSpace).
2) in the input stringNo spaces。
3)Special InputTest (the string is a null pointer, the string is an empty string, the string has only one empty characters, and only a contiguous number of spaces in the string).

Test code:

void Test (char* testname, char string[], int length, char expected[]) {if (testname! = NULL) printf ("%s begins:"    , testname);    Replaceblank (string, length);    if (expected = = NULL && string = = null) printf ("passed.\n");    else if (expected = = NULL && string! = null) printf ("failed.\n");    else if (strcmp (string, expected) = = 0) printf ("passed.\n"); else printf ("failed.\n");}    Space in the middle of the sentence void Test1 () {const int length = 100;    Char string[length] = "Hello World"; Test ("Test1", string, Length, "Hello%20world");}    Space at the beginning of the sentence void Test2 () {const int length = 100;    Char string[length] = "HelloWorld"; Test ("Test2", string, Length, "%20helloworld");}    Space at the end of the sentence void Test3 () {const int length = 100;    Char string[length] = "HelloWorld"; Test ("Test3", string, Length, "helloworld%20");}    There are two spaces in a row void Test4 () {const int length = 100;    Char string[length] = "Hello World"; Test ("Test4", string, length, "Hello%20%20woRld ");} Incoming nullvoid Test5 () {Test ("Test5", NULL, 0, NULL);}    The passed-in content is empty for the string void Test6 () {const int length = 100;    Char string[length] = ""; Test ("Test6", string, Length, "");}    The passed-in content is a space of string void Test7 () {const int length = 100;    Char string[length] = ""; Test ("Test7", string, Length, "%20");    The passed-in string has no space void Test8 () {const int length = 100;    Char string[length] = "HelloWorld"; Test ("Test8", string, Length, "HelloWorld");}    The string passed in is all spaces void Test9 () {const int length = 100;    Char string[length] = ""; Test ("Test9", string, Length, "%20%20%20");}

Main function

int _tmain (int argc, _tchar* argv[]) {    Test1 ();    Test2 ();    Test3 ();    Test4 ();    Test5 ();    Test6 ();    Test7 ();    Test8 ();    Test9 ();    return 0;}

The effect is as follows:



Reference: Huang. "Sword refers to an offer name Enterprise interviewer explaining typical programming problem". 2012. Electronic industry Publishing house

Alternate spaces in C + +

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.