C language Lookup string substring return position __c language

Source: Internet
Author: User

The main idea of the

is to continually remove the temporary substring temp_str from the str1 of the parent string and to compare the substring str2 with the string length. No substring found, returned-1, the substring was successfully found, and the position of the substring's first letter in the parent string was returned, starting at 0.

#include <stdio.h> #include <string.h> char temp_str[30];
    Temporary substring void readstrunit (char * str,char *temp_str,int idx,int len)//Gets the temporary substring {int index = 0, equal to the substring length from the parent string;
    for (index; index < len; index++) {Temp_str[index] = Str[idx+index];
} Temp_str[index] = ';
    int Getsubstrpos (char *str1,char *str2) {int idx = 0;
    int len1 = strlen (STR1);

    int len2 = strlen (STR2);
    if (Len1 < len2) {printf ("Error 1 \ n");//substring longer than the parent string return-1;    while (1) {readstrunit (STR1,TEMP_STR,IDX,LEN2);      The temporary substring if (strcmp (STR2,TEMP_STR) ==0) break is continuously updated from the IDX position of the parent string;                                  If the temporary substring and substring are consistent, end the cyclic idx++;                 Change the position of the temporary substring from the parent string if (IDX&GT;=LEN1) return-1;    If the IDX has exceeded the length of the parent string, the parent string does not contain the substring} return idx;
    Returns the position of the first character of the substring in the parent string int main () {char *str1 = ' Abcdefghijk ';
    Char *str2 = "Def";
    int i = 0;
i = Getsubstrpos (STR1,STR2);    if (i<0) {printf ("not found\n");
    else {printf ("i =%d\n", i);
return 0;
 }
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.