c语言:写出一通用函数,该函数从一个字符指针数组中寻找一个指定的字符串,若找到,返回1;找不到则返

c语言:写出一通用函数,该函数从一个字符指针数组中寻找一个指定的字符串,若找到,返回1;找不到则返回0;谢谢!

//如果找到则返回在长字符串中的起始位置, 若找不到则返回-1
//要返回1或0, 改一下就可以了
int find(char* source, char* target)
{
int i,j;
int s_len=strlen(source);
int t_len=strlen(target);
if(t_len>s_len)
{
return -1;
}
for(i=0;i<=s_len-t_len;i++)
{
j=0;
int flag=1;
if(source[i]==target[j])
{
int k,p=i;
for(k=0;k<t_len;k++)
{
if(source[p]==target[j])
{
p++;
j++;
continue;

}
else
{
flag=0;
break;
}
}
}
else
{
continue;
}
if(flag==1)
{
return i;
}
}
return -1;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-06
现在主函数里用FOR循环将指定的字符串逐一赋入字符指针数组,在主函数之前来个声明,最后用While语句就行了
第2个回答  2014-01-06
/***********************************************************/*程序名称:/*程序员:/*编程时间:2013-12-29/*程序功能:输入多个字符串,按字母顺序排序后输出,/* 输入要查找的字符串,输出其排序后的位置。/*********************************************************/
//头文件声明#include <stdio.h>#include <string.h>#define N 10
//函数声明void Compare(char aComp[][100]);void Searching(char aComp[][100],char c[100]);
void main(){ char a[10][100]; int i; char s[100]; for(i=0;i<10;i++) { printf("The string %d :", i+1); gets(a[i]);//读取函数 } //调用函数比较字符串 Compare(a); //输出比较后字符串 printf("\nThe change strings are:\n\n"); for(i=0;i<10;i++) printf("The No.%d string is:%s\n",i+1,a[i]); //查询函数的位置 printf("\n"); printf("Please input the string what you want to find:\n"); gets(s); //调用函数求字符串所在的位置 Searching(a,s); printf("\n"); }//end of the main
/***************************************************************************/*程序员:/*函数名称:Compare/*函数功能:比较字符串的大小/*函数参数:1.指针/*编程时间:2013-12-31/***************************************************************************/void Compare(char aComp[][100]){ char temp[100];//中介值设定 //冒泡排序 int i,j; for(i=0;i<N-1;i++) for(j=i+1;j<N;j++) if(strcmp(aComp[i],aComp[j])==1) { strcpy(temp,aComp[i]); strcpy(aComp[i],aComp[j]); strcpy(aComp[j],temp); } }//end of the Compare
/************************************************/*程序员:/*函数名称:Searching/*函数功能:输入要查找的字符串,输出其排序后的位置。/*函数参数:1.指针/*编程时间:2013-12-31/***********************************************/void Searching(char aComp[][100],char c[100]){ int i; //求字符串所在的位置 for(i=0;i<N-1;i++) { if(strcmp(c,aComp[i])==0) printf("The string is NO.%d.\n",i+1); } }//end of the Searching

差不多自己改改,大体就是这样。。。
多了一个排序,你可以去掉,不过最好注释掉,要用时候方便。。。本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网