This question requires the implementation of a function that, for a given string and two characters, prints out all the characters in the given string starting from the position matching the first character to the position matching the second character.
Function interface definition:
char *match( char *s, char ch1, char ch2 );
The function match
should print all characters s
from ch1
to ch2
and return ch1
the address.
Sample Referee Test Procedure:
#include <stdio.h> #define MAXS 10 char *match( char *s, char ch1, char ch2 ); int main() { char str[MAXS], ch_start, ch_end, *p; scanf("%s\n", str); scanf("%c %c", &ch_start, &ch_end); p = match(str, ch_start, ch_end); printf("%s\n", p); return 0; } /* 你的代码将被嵌在这里 */
Input example 1:
program
r g
Output sample 1:
rog
rogram
Input example 2:
program
z o
Output sample 2:
(空行)
(空行)
Input example 3:
program
g z
Output sample 3:
gram
gram
char *match( char *s, char ch1, char ch2 )
{
//定义变量存储找到时的地址方便返回
char* ret;
//先查找ch1
while(*s!=ch1&&*s!='\0')
{
s++;
}
//如果没有找到就不会继续去查找ch2,如果找到接下来查找ch2
if(*s!='\0')
{
//记录地址
ret=s;
//查找ch2
while(1)
{
if(*s=='\0')
{
break;
}
printf("%c",*s);
if(*s==ch2)
{
break;
}
s++;
}
}
printf("\n");
return ret;
}