C++末尾匹配(C与C++解决)

CSDN论坛上网友的提问,如下:

C语言版本:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
 
#define LEN 1001
 
int str_case_cmp(char *src, char *dst)
{
    for(; toupper(*src) == toupper(*dst); src++, dst++)
    {
        if(*src == '\0') return 0;
    }
     
    return *src - *dst;
}
 
 
int main(void)
{
    int result = 0;
    char src[LEN], dst[LEN];
     
    fgets(src, LEN, stdin);
    fgets(dst, LEN, stdin);
     
    if(strlen(src) <= strlen(dst))
    {
        if(str_case_cmp(src, dst - strlen(src) + strlen(dst)) == 0) result = 1;
    }
    else
    {
        if(str_case_cmp(src + strlen(src) - strlen(dst), dst) == 0) result = 1;
    }
     
    printf("%s\n", result == 1 ? "True" : "False");
     
    return 0;
}
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define LEN 1001

int main(void)
{
	int result = 0;
	char src[LEN], dst[LEN];
	
	fgets(src, LEN, stdin);
	fgets(dst, LEN, stdin);
	
	char *s = src + strlen(src);
	char *d = dst + strlen(dst);
	
	for(; toupper(*s) == toupper(*d) && s >= src && d >= dst; s--, d--);
	
	if(s < src || d < dst) result = 1;
	
	printf("%s\n", result == 1 ? "True" : "False");
	
	return 0;
}

C++语言版本:

#include <cctype>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{
	int result = 0;
	string src, dst;

	getline(cin, src);
	getline(cin, dst);

	transform(src.begin(), src.end(), src.begin(), toupper);
	transform(dst.begin(), dst.end(), dst.begin(), toupper);

	reverse(src.begin(), src.end());
	reverse(dst.begin(), dst.end());

	if (src.size() >= dst.size())
	{
		if (src.compare(0, dst.size(), dst) == 0) result = 1;
	}
	else
	{
		if (dst.compare(0, src.size(), src) == 0) result = 1;
	}

	cout << (result == 1 ? "True" : "False") << endl;

	return 0;
}
#include <cctype>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{
	int result = 0;
	string src, dst;

	getline(cin, src);
	getline(cin, dst);

	transform(src.begin(), src.end(), src.begin(), [](int c) {return toupper(c); });
	transform(dst.begin(), dst.end(), dst.begin(), [](int c) {return toupper(c); });

	reverse(src.begin(), src.end());
	reverse(dst.begin(), dst.end());

	if (src.size() >= dst.size())
	{
		if (src.compare(0, dst.size(), dst) == 0) result = 1;
	}
	else
	{
		if (dst.compare(0, src.size(), src) == 0) result = 1;
	}

	cout << (result == 1 ? "True" : "False") << endl;

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值