C程序设计语言-练习4-1

练习4-1 编写函数strindex(s,t),他返回字符串t在s中最右边出现的位置

 1 #include <iostream>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 
 6  
 7 //这个是书上的代码
 8 //返回字符串t在s中第一次出现的位置
 9 int StrIndex(char s[], char t[])
10 {
11     for(int n = 0; s[n] != '\0'; n++)
12     {
13         int i,j;
14         for(i = n, j = 0; s[i] == t[j] && t[j] != '\0'++i, ++j)
15             ;
16         if(t[j] == '\0' && j > 0//j>0是考虑t是空串
17             return n;
18     }
19     return -1;
20 }
21 
22 
23 //返回字符串t在s中最右边出现的位置
24 int StrIndex2(char s[], char t[])
25 {
26     for(int n = strlen(s)-1; n >= 0; n--)
27     {
28         int i, j;
29         for(i = n, j = strlen(t)-1; j > 0 && s[i] == t[j] ; --i, --j)
30             ;
31         if(j == 0)
32             return i;
33     }
34     return -1;
35 }
36 int main()
37 {       
38     char s[100= {"abcdefg"};
39     char t[10= {""};
40     cout << StrIndex2(s, t) << endl;
41     return 0;    
42 }
43 


posted on 2010-07-27 20:37  ewee  阅读(334)  评论(0编辑  收藏  举报

导航