本题要求实现一个函数,对给定的一个字符串和两个字符,打印出给定字符串中从与第一个字符匹配的位置开始到与第二个字符匹配的位置之间的所有字符。
函数接口定义:
char *match( char *s, char ch1, char ch2 );
函数match
应打印s
中从ch1
到ch2
之间的所有字符,并且返回ch1
的地址。
裁判测试程序样例:
#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;
}
/* 你的代码将被嵌在这里 */
输入样例1:
program
r g
结尾无空行
输出样例1:
rog
rogram
结尾无空行
输入样例2:
program
z o
输出样例2:
(空行)
(空行)
输入样例3:
program
g z
输出样例3:
gram
gram
思路:分别找到pla1,pla2,对pla1和pla2的存在性进行讨论
注意:1、sample2中,返回s+len是因为,字符串末尾自带'\0',所以输出后什么都看不见
2、理论上不能返回NULL,因为不能访问空指针,但是PTA测评机有输出,也许NULL的位置存的字符串就是(NULL),或者测评程序有特判。
char *match( char *s, char ch1, char ch2 ){
int i = 0, len = 0;
int pla1 = -1, pla2 = -1;
while(s[i] != '\0'){
len++;
i++;
}
for(int i=0; i<len; i++){
if(s[i] == ch1){
pla1 = i;
break;
}
}
for(int i=0; i<len; i++){
if(s[i] == ch2){
pla2 = i;
break;
}
}
if(pla1 == -1) {
printf("\n");
return s+len;
}
else {
if(pla2 == -1) {
printf("%s\n", s+pla1);
}
else {
for(int i=pla1; i<=pla2; i++)
printf("%c", s[i]);
printf("\n");
}
return s+pla1;
}
}