遇到了本章的第二个难点,也是读本科时候一直不会思考的问题。
思路分析:
设字符串2的长度为t,首先在字符串1中寻找字符串2的首字母,找到后,比较首字母到首字母加t位置的这一段子串和字符串2是否相同,如果相同,就返回字符串1中子串的地址,如果找不到,就返回空指针。
代码如下:
#include <stdio.h>
#include "string.h"
#define SIZE 30
char * string_in(char * str1 , char * str2);
int main(int argc, const char * argv[]) {
char test2[SIZE];
char test1[SIZE];
char * result;
puts("input string1:");
gets(test1);
puts("input string2:");
gets(test2);
result = string_in(test1,test2);
if(result){
puts("we get it ");
printf("%s is at %p",test2,result);
}else{
puts("no no no");
}
return 0;
}
char * string_in(char * str1 , char * str2)
{
char * repo = NULL;
int length1 = 0;
int length2 = 0;
int i=0;
int j=0;
length1 = strlen(str1);
length2 = strlen(str2);
for(i=0;i<length1;i++){
if(*(str1+i) == *str2){
repo = str1+i;
j=0;
for(j=1 ; j<length2 ; j++){
if(*(repo+j)!=*(str2+j)){
repo = NULL;
break;
}
}
if(j == length2){
return repo;
}
}
}
return repo;
}