C语言编程-阿尔法编程练习题-查找子串?

Python019

C语言编程-阿尔法编程练习题-查找子串?,第1张

#include<stdio.h>

#include<stdlib.h>

int search(char *str,char *substr)

{

/*_________________*/

int c[50],k

char *p,*q

int i=0,len=0,lct=1,j

q=substr

for(*q!='\0'q++)

{

len=len+1

}

p=str

q=substr

do

{

if(*p!=*q)

{

p++

lct++

}

else

{

while((*q!='\0')&&(*q==*p))

{

q++

p++

lct++

}

if(*q=='\0')

{

c[i]=lct-len//用来记录子串出现的位置;

i++

}

}

q=substr

}

while(*p!='\0')

if(i==0)

k=-1

else

k=c[0]

return k

/*__________________*/

}

int main()

{

char *str="abcdefghijklmn",*substr="def"

int i=0

i=search(str,substr)

printf("%d\n",i)

return 0

}

你虽然没有贴出strstr() 函数的内容,但如果strstr()函数返回的是b字符串的第一个字符在a字符串中出现的地址,那么就要用“【返回值】-【字符串a首字母的地址】+1”了。

举例说明如下:

假设a="iloveChina."

b="Chi"

不妨假定a的储存地址是1001,那么各个字符的储存地址分别是:

i—1007,l—1008,o—1009,v—1010,e—1011,C—1012,h—1013,i—1014,n—1015,a—1016,. —1017

现在要查找Chi,显然是能够查到的,这时函数的返回值将会是C的地址1012,我们知道a的值是字母i的地址——1007。经过下面的计算:

1012-1007+1=6

就得到Chi在字符串iloveChina. 中出现的位置是6(代表从第六个字符出现)。

有什么问题请留言。

#include

#include

int substring(char *str,char *str1)//函数原型

int main(void)

{

char str[64]={0}

char str1[16]={0}

int i,j,x

printf("please put the string\n")

gets(str)//输入的原字符串

puts(str)

printf("\n")

printf("please put the string1 \n")

gets(str1)//输入的字符串中的子串

puts(str1)

printf("\n")

i=strlen(str)//原字符串长度

j=strlen(str1)//子串长度

printf("the string lenth is %d\n",i)

printf("the string lenth is %d\n",j)

x=substring(str,str1)

printf("then anwser is %d\n",x)

return 0

}

int substring(char *str,char *str1)

{

int x=0

char *p//任意附个初始值

do{

p=strstr(str,str1)//1.p指针指向strstr的返回值。3.再一次循环到 这里函数的参数发生变化,p重新指向strstr返回值,如此循环。

if(p != NULL) {

str=p+1//2.str同样指向strstr返回值p的下一个地址。

x=x+1

}

}while(p!=NULL)

return x

}

另一种方法,不用库函数来实现,来自他人。。。

int substring1(char *str,char * str1,int n,int m)

{

int i,j=0,k

int x=0

for(i=0i<=n-mi++) {

k = i

while (1) {

if (str[k] != str1[j] ) {

j=0

break

} else if (str1[j+1] == '\0') {

x++

j=0

break

} else {

k++

j++

}

}

}

return x

}