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


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

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

具体代码如下:

findstr.c

  1. /** 
  2.  
  3. Author: snowdream <yanghui1986527@gmail.com> 
  4.  
  5. Data: 2012.03.05 
  6.  
  7. Description: 
  8. 假设一个主要字符串“Hello World!”,和一个子字符串"World". 
  9. 在大小写敏感的前提下,如果主字符串包含子字符串,请写出一个函数 
  10. 计算出该子字符串在主字符串中的索引index。否则返回 -1 作为索引值。 
  11.  
  12. */  
  13.   
  14.   
  15.   
  16.   
  17. #include <stdio.h>   
  18.   
  19. int findstr(char* substr,char* mainstr)  
  20. {  
  21.     int index = -1;  
  22.       
  23.     for(int i = 0; *(mainstr+i)!='\0';i++)  
  24.     {  
  25.         for(int j = 0; *(substr+j)!='\0';j++)  
  26.         {  
  27.             if(*(substr+j) != *(mainstr+i+j))  
  28.                 break;  
  29.               
  30.             if(*(substr+j+1) =='\0' )  
  31.                 index = i;  
  32.         }  
  33.           
  34.        if(index != -1)  
  35.            break;  
  36.     }      
  37.       
  38.     return index;  
  39. }  
  40.   
  41.   
  42. int main()  
  43. {  
  44.     int index = -1;   
  45.     int index1 = -1;  
  46.       
  47.     char* mainstr = "Hello World!";  
  48.     char* substr = "cctv";    
  49.     char* substr1 = "World";  
  50.      
  51.     index = findstr(substr,mainstr);  
  52.     index1 = findstr(substr1,mainstr);  
  53.      
  54.     printf("The index of %s in %s is: %d\n",substr,mainstr,index);  
  55.     printf("The index of %s in %s is: %d\n",substr1,mainstr,index1);  
  56.   
  57.     return 0;  
  58. }  

在Ubuntu下编译运行:

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

相关内容