习题11-5 指定位置输出字符串 (20 分)

本题要求实现一个函数,对给定的一个字符串和两个字符,打印出给定字符串中从与第一个字符匹配的位置开始到与第二个字符匹配的位置之间的所有字符。

函数接口定义:

char *match( char *s, char ch1, char ch2 );

函数match应打印s中从ch1ch2之间的所有字符,并且返回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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值