Implementation of the C-Series function prototype-strstr (char * STR, char * substr)

Source: Internet
Author: User

Ideas:

1. If the last character of the string is '\ 0', it can be used as a critical condition.

2. When * Str! = '\ 0', judge whether * P is equal to * q. If it is equal, move two pointers. If the last * q pointer reaches the boundary, the entire match is successful, return res directly. Otherwise, move the primary string pointer.


# Include <iostream>


Char * mystrstr (char * STR, char * substr ){

While (* Str! = '\ 0 '){

Char * P = STR;

Char * q = substr;

Char * res = NULL;

If (* P = * q ){

Res = P;

While (* Q! = '\ 0' & * P = * q ){

P ++;

Q ++;

}

If (* q = '\ 0 ')

Return res;

}

STR ++;

}

Returnnull;

}


Int main (INT argc, constchar * argv [])

{

Char * S1 = "abcdefghijklmn ";

Char * S2 = "BCD ";


// Search for string 2 in string S1. If the return position is found, otherwise null is returned.

Char * res = mystrstr (S1, S2 );

If (res! = NULL ){

Printf ("% s", Res );

} Else {

Printf ("not ");

}

Printf ("\ n ");

Return0;

}


Result:


Implementation of the C-Series function prototype-strstr (char * STR, char * substr)

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.