0%

2-5:返回字符串s2中的任一字符在字符串s1中第一次出现的位置

文章时效性提示

本文发布于 470 天前,部分信息可能已经改变,请注意甄别。

編写函数any(s1,s2),将字符串s2中的任一字符在字符串s1中第一次出现的位置作为结果返回。如果s1中不包含s2中的字符,则返回-1。(标准库函数strpbrk具有同样的功能,但它返回的是指向该位置的指针。)

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
int any(char* s1,char* s2)
{
    int i = 0;
    int j = 0;
    int ret = 1;
    for (i=0; s1[i]!='\0'; i++)
    {
        for (j=0; s2[j]!='\0'; j++)
        {
            if (s1[i] == s2[j])
            {
                return ret;
            }
        }
        ret++;
    }
    return -1;
}
int main() {
    char s1[10] = "fwehqasceq";
    char s2[3] = "ca";
    int ret = any(s1,s2);
    printf("%d\n",ret);
    return 0;
}