给定两个字符串 A 和 B,本题要求你输出 A+B,即两个字符串的并集。要求先输出 A,再输出 B,但重复的字符必须被剔除。
输入格式:
输入在两行中分别给出 A 和 B,均为长度不超过 106的、由可见 ASCII 字符 (即码值为32~126)和空格组成的、由回车标识结束的非空字符串。
输出格式:
在一行中输出题面要求的 A 和 B 的和。
输入样例:
This is a sample test
to show you_How it works
输出样例:
This ampletowyu_Hrk
总结:
可以利用字符串的查找、或者定义额外的字符数组进行已有字符的判断,筛去已有字符。
代码:
第一种:利用字符串的查找。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
string textStr[2], result;
getline(cin, textStr[0]);
getline(cin, textStr[1]);
for(int j=0;j<2;j++) {
for(int i=0;i<textStr[j].length();i++) {
if( result.find(textStr[j][i]) == string::npos )
result += textStr[j][i];
}
}
cout << result << endl;
return 0;
}
第二种:利用数组对已存储的字符进行筛选。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
string textStr[2], result;
getline(cin, textStr[0]);
getline(cin, textStr[1]);
bool textChar[200] = {0};
for(int j=0;j<2;j++) {
for(int i=0;i<textStr[j].length();i++) {
if( textChar[ textStr[j][i] ] == false ) {
result += textStr[j][i];
textChar[ textStr[j][i] ] = true;
}
}
}
cout << result << endl;
return 0;
}