本题要求实现一个函数, 对给定的一个字符串和两个字符, 打印出给定字符串中从与第一个字符匹配的位置开始到与第二个字符匹配的位置之间的所有字符.
函数接口定义:
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
代码:
- char *match( char *s, char ch1, char ch2 ) {
- char *t = "";// 初始空串
- int i = 0,c = -1;
- while(s[i] && s[i] != ch1) i ++;
- if(s[i] == ch1) {
- t = s + i;
- c = i;
- }
- while(s[i] && s[i] != ch2) i ++;
- if(s[i] != ch2) i --;// 别多了末尾的 0
- if(c != -1) {
- while(c <= i) putchar(s[c ++]);
- }
- putchar('\n');
- return t;
- }
来源: http://www.bubuko.com/infodetail-3398745.html