歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用C語言編寫函數計算子字符串substr在主字符串mainstr中的索引值

用C語言編寫函數計算子字符串substr在主字符串mainstr中的索引值

日期:2017/3/1 10:26:28   编辑:Linux編程

在大小寫敏感的前提下,用C語言編寫函數計算子字符串substr在主字符串mainstr中的索引值。

如果substr完全包含在mainstr中,請計算出索引值。否則,返回-1.

具體代碼如下:

findstr.c

  1. /**
  2. Author: snowdream <[email protected]>
  3. Data: 2012.03.05
  4. Description:
  5. 假設一個主要字符串“Hello World!”,和一個子字符串"World".
  6. 在大小寫敏感的前提下,如果主字符串包含子字符串,請寫出一個函數
  7. 計算出該子字符串在主字符串中的索引index。否則返回 -1 作為索引值。
  8. */
  9. #include <stdio.h>
  10. int findstr(char* substr,char* mainstr)
  11. {
  12. int index = -1;
  13. for(int i = 0; *(mainstr+i)!='\0';i++)
  14. {
  15. for(int j = 0; *(substr+j)!='\0';j++)
  16. {
  17. if(*(substr+j) != *(mainstr+i+j))
  18. break;
  19. if(*(substr+j+1) =='\0' )
  20. index = i;
  21. }
  22. if(index != -1)
  23. break;
  24. }
  25. return index;
  26. }
  27. int main()
  28. {
  29. int index = -1;
  30. int index1 = -1;
  31. char* mainstr = "Hello World!";
  32. char* substr = "cctv";
  33. char* substr1 = "World";
  34. index = findstr(substr,mainstr);
  35. index1 = findstr(substr1,mainstr);
  36. printf("The index of %s in %s is: %d\n",substr,mainstr,index);
  37. printf("The index of %s in %s is: %d\n",substr1,mainstr,index1);
  38. return 0;
  39. }

在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
Copyright © Linux教程網 All Rights Reserved