C language: customizes a function for searching strings, similar to strstr (), string. hstrstr in & lt; string. h & gt;

Source: Internet
Author: User

C language: customizes a function for searching strings, similar to strstr (), string. hstrstr in <string. h>.

// Customize a string to search for the standard library function strstr ()

# Include <stdio. h>

# Include <string. h>

Char * myStrstr (char * str1, char * str2 );

Int main ()

{

Char * str1 = "hello worl world ld ";

Char * str2 = "world ";

Puts (myStrstr (str1, str2 ));

Return 0;

}

Char * myStrstr (char * str1, char * str2)

{

Static int count = 0;

Const char * p = str2;

Char * pt;

While (* (str2 ++ ))

{

While (* (str1 ++ ))

{

// If the first character of str2 and str1 is the same, and then the second character is compared, count is accumulated.

If (* (str2-1) = * (str1-1 ))

{

Count ++;

Break;

}

// If the first character of str2 and str1 is different, traverse str1 until the end

Else if (* (str2-1 )! = * (Str1-1) & count <strlen (p ))

{

Continue;

}

// If the first few characters of str2 and str1 are the same, str2 starts from scratch.

Else

{

Str2 = str2-count;

Break;

}

}

If (* str2 = '\ 0' & count = strlen (p ))

Pt = str2-count; // locate the string, move the pointer to the first address of str2 and return

Else

Pt = NULL; // the string is not found and NULL is returned.

}

Return pt;

}

 

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.