char *find_char(char const *source,char const *chars); 不允许使用库函数。题目意思是:在chars中的字符如果在source中有,就使指针指向第一个出现的source位置。以下是我写的:
#include <iostream.h>
size_t str_len( char const *str);
char *find_char(char const *source,char const *chars);
void main()
{
char src[20]="ABCDEF";
char find[20]="XRQ E";
const char *dst;
if ((dst=find_char(src,find))!=NULL)
{
cout<<*dst<<endl;
}
else
{
cout<<"返回NULL\n";
}
}
char *find_char(char const *source,char const *chars)
{
int len_chars=str_len(chars);
int len_source=str_len(source);
for (int i=0;i<len_chars;i++)
for (int j=0;j<len_source;j++)
{
if((*(source+j))==(*(chars+i)))
return (char*) (source+j);
}
return NULL;
}
/*计算字符串长度*/
size_t str_len( char const *str)
{
int length=0;
while (*str++!='\0')
{
length++;
}
return length;
}
百度百科上的strpbrk源码:
extern
char
*
strpbrk
(
const
char
*s1,
const
char
*s2);
char
*
strpbrk
(
const
char
* cs,
const
char
* ct)
{
const
char
*sc1,*sc2;
for
( sc1 = cs; *sc1 !=
'\0'
; ++sc1)
{
for
( sc2 = ct; *sc2 !=
'\0'
; ++sc2)
{
if
(*sc1 == *sc2)
{
return
(
char
*) sc1;
}
}
}
return
NULL;
}
举例:
// strpbrk.c
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
main()
{
char
*s1=
"Welcome To Beijing"
;
char
*s2=
"lco"
;
char
*p;
system
(
"cls"
);
/*Example 1*/
p=
strpbrk
(s1,s2);
if
(p)
{
printf
(
"%s\n"
,p);
/*Output "lcome To Beijing"*/
}
else
{
printf
(
"Not Found!\n"
);
}
/*Example 2*/
p=
strpbrk
(s1,
"Da"
);
if
(p)
{
printf
(
"%s"
,p);
}
else
{
printf
(
"Not Found!"
);
/*"Da" is not found*/
}
getchar
();
return
0;
}
他没有用字符长度,直接判断是否到达nul,还有看他初始化用指针形式
char
*s1=
"Welcome To Beijing"
;