The C Programming Language 练习题2-5

来源:互联网 发布:皮皮麻将算法 编辑:程序博客网 时间:2024/05/16 07:10

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

题目分析
不太理解任一字符如何操作,就把每个字符在字符串1中的位置都做标注。实现方法跟2-4类似。

编程实现

#include <stdio.h>#define MAXLINE 1000int positionc(char s1[], char s2[], int p[]);int main(){    int i, positions[MAXLINE];    char c, sfirst[MAXLINE], ssecond[MAXLINE];    i = 0;    printf("Please input string1:");    while ((c = getchar()) != '\n')        sfirst[i++] = c;    sfirst[i] = '\0';    i = 0;    printf("Please input string2:");    while ((c = getchar()) != '\n')        ssecond[i++] = c;    ssecond[i] = '\0';    positionc(sfirst, ssecond, positions);    i = 0;    while (ssecond[i] != '\0')    {        printf("%c\t%d\n",ssecond[i], positions[i]);        i++;    }}int positionc(char s1[], char s2[], int p[]){    int m, n, l, r;    n = 0;    while (s2[n] != '\0')        {            p[n] = 0;            m = l = 0;            while (s1[m] != '\0')                {                    if (s1[m] != s2[n] && s1[m+1] != '\0')                        l++;                    else if ( s1[m] == s2[n])                        {                            p[n] = l;                            break;                        }                    else if (s1[m] != s2[n] && s1[m + 1] == '\0')                        {                            p[n] = -1;                            break;                        }                    m++;                }            if (s1[m] == '\0' && l == 0)                        p[n] = -1;            n++;        }}