String substring search strstr

Source: Internet
Author: User

Problem:

Function Name: strstr function prototype: char * strstr (const char * str1, const char * str2); Syntax: * strstr (str1, str2) str1: target string expression to search. str2: the string expression to find. return Value: This function returns the address of str2 in str1 for the first time. If no address is found, the return value is null: charstr[]= "1234xyz" ; char *str1= strstr (str, "34" ); Get str1 = "34xyz" 

Method 1:

One pointer scan, when the first letter is the same, the two pointers scan two strings for comparison.

The Code is as follows:

#include <stdio.h>#include <string.h>#include <assert.h>char* mystrstr(const char* str1,const char* str2)//str1 is the original string {    assert(str1 != NULL);    if(str2 != NULL) return (char*)str1;    while(str1 != ‘\0‘){        if(*str1 != *str2) str1++;        else{            char* ori = str1;            char* des = str2;            while(*des != ‘\0‘){                if(*ori == *des){                    ori++;des++;                }                else break;            }            if(*des == ‘\0‘) return str1;        }    }    return NULL;}int main(){    char ori[]="sdggdfhhttyusdfge";    char des[]="ttyu";    char* ret=mystrstr(ori,des);    printf("%s\n", ret);    return 0;}

The result is

[[Email protected] desktop] #./A. Out
Ttyusdfge

 

Method 2:

Similar methods:

#include <stdio.h>#include <string.h>char* mystrstr(const char* str1,const char* str2)//str1 is the original string {    int len2 = strlen(str2);    int len1 = strlen(str1);    if(!len2) return (char*)str1;    while(len1 >= len2){        len1--;        if(!strcmp(str1,str2,len2)) return (char*)str1;        str1++;        }    }    return NULL;}int main(){    char ori[]="sdggdfhhttyusdfge";    char des[]="ttyu";    char* ret=mystrstr(ori,des);    printf("%s\n", ret);    return 0;}

The result is

[[Email protected] desktop] #./A. Out
Ttyusdfge

 

String substring search strstr

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.