用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值

来源:互联网 发布:ubuntu中国官网 编辑:程序博客网 时间:2024/06/09 17:52

在大小写敏感的前提下,用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值。

如果substr完全包含在mainstr中,请计算出索引值。否则,返回-1.


具体代码如下:

findstr.c

/**Author: snowdream <yanghui1986527@gmail.com>Data: 2012.03.05Description:假设一个主要字符串“Hello World!”,和一个子字符串"World".在大小写敏感的前提下,如果主字符串包含子字符串,请写出一个函数计算出该子字符串在主字符串中的索引index。否则返回 -1 作为索引值。*/#include <stdio.h>int findstr(char* substr,char* mainstr){    int index = -1;        for(int i = 0; *(mainstr+i)!='\0';i++)    {        for(int j = 0; *(substr+j)!='\0';j++)        {            if(*(substr+j) != *(mainstr+i+j))                break;                        if(*(substr+j+1) =='\0' )                index = i;        }               if(index != -1)           break;    }            return index;}int main(){    int index = -1;     int index1 = -1;        char* mainstr = "Hello World!";    char* substr = "cctv";      char* substr1 = "World";       index = findstr(substr,mainstr);    index1 = findstr(substr1,mainstr);       printf("The index of %s in %s is: %d\n",substr,mainstr,index);    printf("The index of %s in %s is: %d\n",substr1,mainstr,index1);    return 0;}


在ubuntu下编译运行:

snowdream@snowdream:~$ gcc findstr.c -std=gnu99 -o findstr -gsnowdream@snowdream:~$ ./findstr The index of cctv in Hello World! is: -1The index of World in Hello World! is: 6