编写函数any(s1,s2),将字符串s2中的任意字符在字符串s2中第一次出现的位置作为结果返回,如果s1中有不包含在s2中的字符,返回-1。
代码如下:
int any(char s1[],char s2[]){
int i,j;
for(i = 0; s2[i]!='\0';i++){
for(j = 0;s1[j] != '\0';j++){
if(s1[j] == s2[i]){
return j+1;
}
}
}
return -1;
}
int main(){
char s1[] = "abcdefg";
char s2[] = "d";
printf("%d\n",any(s1,s2));
return 0;
}
注意,只能输出s2中第一个符合条件的字符位置,若需输出其他位置,则代码如下:
int any(char s1[],char s2[],int n){
int j;
for(j = 0;s1[j] != '\0';j++){
if(s1[j] == s2[n]){
return j+1;
}
}
return -1;
}
int main(){
int n;
char s1[] = "abcdefg";
char s2[] = "avdffj";
scanf("%d",&n);
printf("%d\n",any(s1,s2,n-1));
return 0;
}
注意,n是s2中字符的位置,若该字符在s1中不存在,则返回-1,否则返回s1的位置下标。