字符串查找

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。

如果 source = "source" 和 target = "target",返回 -1。
如果 source = "abcdabcdefgem" 和 target = "bcd",返回 1。

 1 #include<iostream>
 2 #include<string.h>
 3 using namespace std;
 4 int main(){
 5     char source[50], target[50];
 6     int w=-1, j=0, n=0; //n记录匹配的个数,w记录target在source中最早出现的位置 
 7     cin>>source>>target;
 8     int sn=strlen(source);
 9     int tn=strlen(target);
10     if(tn<=sn){    //tn>sn的话一定不匹配,所以不考虑那种情况 
11         for(int i=0; i<sn; i++){
12             if(source[i]==target[j]){//找到与target中第一个字符相同时的位置i ,注意,之前已经初始化j=0了 
13                 w=i;//记录位置 
14                 while(source[i]==target[j]){
15                     n++;//记录匹配的个数,不匹配了就跳出while语句 
16                     if(j==tn-1){//此时target中的所有字符都匹配过了 
17                         break;
18                     }
19                     i++;
20                     j++;
21                 }
22                 if(n==tn){
23                     break;
24                 }else{//匹配到的长度不是target的长度,表示匹配不正确。j=0让target从头开始去比较 
25                     n=0;
26                     w=-1;
27                     j=0;
28                 }
29             }
30         }
31     }
32     
33     cout<<w;
34     
35     return 0;
36 } 

  通过率只有50%,不知道哪里不对

posted @ 2017-09-28 22:11  不呐呐欸  阅读(129)  评论(0)    收藏  举报