从键盘输入字符串1和字符串2(串长不超过50个字符),将在字符串1中出现,但未在字符串2中出现的字符组成一个新的字符串输出,不去掉未出现过的重复字符。
#include<iostream>
#include <unordered_set>
#include <algorithm>
#include <string>
#include <vector>
#include <numeric>
#include <unordered_map>
using namespace std;
int main() {
string str1, str2, str3;
str1 = "aaaaabbbbbcccdd";
str2 = "efaahh";
unordered_set<char> m2;
for (char c : str2)
{
m2.insert(c);
}
for (char c : str1) {
if (m2.find(c)==m2.end())
{
str3 += c;
}
}
cout << str3;
}
(有待思考)#define _CRT_SECURE_NO_WARNINGS
#include
#include
#includeusing namespace std;
void index(char* s1, char* s2)
{
int len ,max = 0;
char temp[50];
while (*s1)
{
while (*s1 == ’ ’ && *s1 != ‘\0’) s1++;//过滤空格;
len = 0;
while (*s1 != ' ' && *s1 != '\0')
{
*(temp + len) = *s1;//不能用*temp=*s1,why?
len++;
s1++;
}
*(temp + len) = '\0';//注意这种方式。
if (len > max)
{
max = len;
strcpy(s2, temp);
}
if (*s1 == '\0') break;
}}
int main()
{
char s1[50],s2[50];cin.get(s1,50); index(s1, s2);
cout << “s2:” << s2;
}用队列的方法输出杨辉三角:#include
using namespace std;
const int maxsize = 100;
typedef struct {
int Q[maxsize];//存放数据
int front, rear;
}sequeue;
sequeue qu;
void setkong(sequeue& qq)
{
qq.front = 0;
qq.rear = 0;
}//置队空
void rudui(sequeue& qq, int x)
{
if (qq.front == (qq.rear + 1) % maxsize)
cout << “overflow\n”;
else
{
qq.Q[qq.rear] = x;
qq.rear = (qq.rear + 1) % maxsize;
}
}
void chudui(sequeue &qq, int& x)
{
if (qq.front == qq.rear)
{
cout << “underflow\n”;
}
else
{
x = qq.Q[qq.front];
qq.front = (qq.front + 1) % maxsize;
}
}
void getfront(sequeue qq, int &x)//读取队头元素
{
if (qq.front == qq.rear)
{
cout << “error!\n”;
}
else
{
x = qq.Q[qq.front];
}
}
int empty(sequeue qq)//判断队列是否为空
{
if (qq.front == qq.rear)
return 1;
else
return 0;
}
void yanghui(int n,sequeue qu)
{
int i, j,s,t;
setkong(qu);
rudui(qu, 1); rudui(qu, 1);
cout << endl;
cout.width(4); cout << 1;
cout.width(4); cout << 1<<endl;
for (i = 2; i <= n; i++)//生成并输出杨辉三角第i~n行的数据
{
rudui(qu, 1);
cout.width(4); cout << 1;
chudui(qu, s);
for (j = 2; j <= i; j++)//处理第i行中间的各数据
{
chudui(qu, t);
rudui(qu, s + t);
cout.width(4); cout << s + t;
s = t;
}
rudui(qu, 1);
cout.width(4); cout << 1<<endl;
}
cout << endl;
}
int main()
{
int m;
cin >> m;
yanghui(m, qu);
}
解决方案:
题目要求输入两个字符串s1和s2,长度都不超过50个字符。从s1中提取出在s2中未出现过的字符组成一个新的字符串输出,不去除未出现的重复字符。
思路:
遍历s1中的每一个字符,判断是否在s2中出现过。
如果未出现过,则将其添加到一个新的字符串中。
最终输出这个新的字符串即可。
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[51], s2[51];
cin.getline(s1, 51);
cin.getline(s2, 51);
char newstr[51] = "";
int len = strlen(s1);
for (int i = 0; i < len; i++)
{
if (strchr(s2, s1[i]) == NULL)
{
strncat(newstr, &s1[i], 1);
}
}
cout << newstr << endl;
return 0;
}
参考资料中的代码是用来取出一个字符串中最长的单词并存入另一个字符串的,与本题没有关系。
Markdown格式返回的代码如上所示。