在大小写敏感的前提下,用C语言编写函数计算子字符串substr在主字符串mainstr中的索引值。如果substr完全包含在mainstr中,请计算出索引值。否则,返回-1.具体代码如下:findstr.c
- /**
-
- Author: snowdream <yanghui1986527@gmail.com>
-
- Data: 2012.03.05
-
- Description:
- 假设一个主要字符串“Hello World!”,和一个子字符串"World".
- 在大小写敏感的前提下,如果主字符串包含子字符串,请写出一个函数
- 计算出该子字符串在主字符串中的索引index。否则返回 -1 作为索引值。
-
- */
-
-
-
-
- #include <stdio.h>
-
- int findstr(char* substr,char* mainstr)
- {
- int index = -1;
-
- for(int i = 0; *(mainstr+i)!=" ";i++)
- {
- for(int j = 0; *(substr+j)!=" ";j++)
- {
- if(*(substr+j) != *(mainstr+i+j))
- break;
-
- if(*(substr+j+1) ==" " )
- 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
",substr,mainstr,index);
- printf("The index of %s in %s is: %d
",substr1,mainstr,index1);
-
- return 0;
- }
在Ubuntu下编译运行:
- snowdream@snowdream:~$ gcc findstr.c -std=gnu99 -o findstr -g
- snowdream@snowdream:~$ ./findstr
- The index of cctv in Hello World! is: -1
- The index of World in Hello World! is: 6