函数strstr的原型是char *strstr(char *str1, char *str2); 其功能是在str1中返回指定字符串str2的第一次出现的位置。
view plaincopy to clipboardprint?01.#include <stdio.h> 02.#include <string.h> 03.int main(void) 04.{ 05. char *str1 = "Borland International", *str2 = "nation", *ptr; 06. ptr = strstr(str1, str2); 07. printf("The substring is: %s/n", ptr); 08. return 0; 09.} 10./* 11.output: 12.The substring is: national 13.*/ #include <stdio.h>#include <string.h>int main(void){ char *str1 = "Borland International", *str2 = "nation", *ptr; ptr = strstr(str1, str2); printf("The substring is: %s/n", ptr); return 0;} /*output:The substring is: national */
下面是实现strstr功能的一种方法。
view plaincopy to clipboardprint?01./* 02.Modification date: 2010-5-28 03.src: abcd efghcd abcdef 04.dst:cd 05.return: cd efghcd abcdef 06.*/ 07.#include <cstdio> 08.#include <cstring>// strlen 09.#include <cassert>// assert 10.#include <conio.h>// getch 11.//#include <cstring>// strstr 12.#define NULL 0; 13.char* strstr(char* src,char* dst) 14.{ 15. printf("call my strstr/n"); 16. // check 17. assert(src); 18. assert(dst); 19. 20. // calculate the each size 21. char *szSrc=src,*szDst=dst; 22. int nSrcSize=strlen(szSrc),nDstSize=strlen(szDst); 23. // check 24. if (nSrcSize<nDstSize) 25. { 26. return NULL;// error 27. } 28. // compare 29. int nCompareCount=nSrcSize-nDstSize+1; 30. int i,j; 31. for (i=j=0; i<nSrcSize && j<nDstSize; ++i) 32. { 33. if (src[i]!=dst[j]) 34. { 35. if (i==nCompareCount-1)// this check can save time 36. { 37. return NULL;// no substring 38. } 39. j=0; 40. } 41. else// to find the first same value 42. { 43. ++j; 44. } 45. } 46. if (j==nDstSize)// absolute equal 47. { 48. return &src[i-nDstSize];// have substring 49. } 50. return NULL;// no substring 51.} 52.int main() 53.{ 54. //char *szSrc = "wcdj is a guy", *szDst = "is"; 55. char szSrc[128]={0},szDst[128]={0}; 56. printf("input src: "); 57. //scanf("%s",szSrc); 58. gets(szSrc); 59. printf("input dst: "); 60. //scanf("%s",szDst); 61. gets(szDst); 62. // call my function 63. char* ptr=strstr(szSrc,szDst); 64. if (ptr) 65. { 66. printf("The substring is: %s/n", ptr); 67. } 68. else 69. { 70. printf("has no substring/n"); 71. } 72. getch(); 73. return 0; 74.}
本文来自博客,转载请标明出处:http://blog.csdn.net/delphiwcdj/archive/2009/09/30/4620793.aspx