您的位置:首页 > 其它

The C Programming Language 练习题2-5

2017-10-02 01:14 344 查看
题目

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

题目分析

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

编程实现

#include <stdio.h>
#define MAXLINE 1000

int 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
!= '\0')
{
p
= 0;
m = l = 0;
while (s1[m] != '\0')
{
if (s1[m] != s2
&& s1[m+1] != '\0')
l++;
else if ( s1[m] == s2
)
{
p
= l;
break;
}
else if (s1[m] != s2
&& s1[m + 1] == '\0')
{
p
= -1;
break;
}
m++;
}
if (s1[m] == '\0' && l == 0)
p
= -1;
n++;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: