C++程序设计(PEARSON版)第三版10.2答案

本文介绍了一个C++程序,该程序能够接收两个字符串作为输入,并找出这两个字符串中的公共字符。程序首先比较两个字符串的长度,然后使用两层循环遍历每个字符串以确定公共字符的位置。最后,程序输出这些公共字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string commonChars(const string & s1,const string &s2)

编写测试程序,提示用户输入两个字符串,打印输出他们的公共字符。下面是样例运行:

Ex1:

Enter a string s1:abcd

Enter a string s2:aecaten
The common characters are ac

Ex2:

Enter a string s1:abcd

Enter a string s2:efg
No common characters

下面的代码在VS2017和Dev-C++上获得通过:

#include "pch.h"
#include <iostream>
#include<string>
#include<algorithm>
using namespace std;
bool compareBM(string s1, string s2)
{
	if (s1.length() >= s2.length())
		return true;
	else
		return false;
}
string refixed(string d)
{
	string::iterator it = d.begin();
	while (it != d.end())
	{
		for (string::iterator helper = it + 1; helper != d.end(); helper++) {
			if (*it == *helper)
			{
				d.erase(helper);
				helper--;
				// 为了使得最后一次字符被删除时,check2不会超出input1的范围。
			}
		}
		it++;
	}
	return d;
}
string commonChars(const string& s1, const string& s2)
{
	bool c;
	string b=s1,d=s1;
	c=compareBM(s1, s2);
	int a[100] = { 0 };
	int k=0;
	if (c == true)
	{
		for (unsigned int i=0;i<s1.length();i++)
		{
			for (unsigned int j = 0; j<s2.length(); j++)
			{
				if (s1[i] == s2[j])
				{
					a[k] = i;
						k++;
				}
			}
		}
					
	}
	else
	{
		for (unsigned int i = 0; i < s2.length(); i++)
		{
			for (unsigned int j = 0;j< s1.length(); j++)
			{
				if (s2[i] == s1[j])
				{
					a[k] = i;
					k++;
				}
			}
		}
	}
	if (k == 0)
		return "No common characters";
	if (c == true)
		b = s1;
	else b = s2;
	for (int i = 0; i < k; i++)
	{
		d[i] = b[a[i]];
	}
	for (int i = k; i < d.length(); i++)
	{
		d[i] = '\0';
	}
	d = refixed(d);
	return "The common characters are "+d;
}
int main()
{
	string s1, s2;
	cout << "Enter a string s1:";
	cin >> s1;
	cout << endl;
	cout << "Enter a string s2:";
	cin >> s2;
	cout<<commonChars(s1, s2);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值