输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
例如:第一个字符串是"They are students.",第二个字符串是”aeiou"。删除之后的第一个字符串变成"Thy r stdnts."。
保证两个字符串的长度均不超过100。
输入两行,每行一个字符串。
输出删除后的字符串。
They are students. aeiou
Thy r stdnts.
#include <stdio.h> #include <string.h> char* delete_char(char *str1,char *str2) //在str1中删除str2中出现的字符 { int flag=1; char str3[101] = {0}; char* s3 = str3; char* s2 = str2; while (*str1) { flag = 1; s2 = str2; while (*s2) { if (*str1==*s2) { flag = 0; break; } s2++; } if (flag == 1) { *s3 = *str1; s3++; } str1++; } return strcpy(str1,str3); } int main() { char str1[101] = ""; char str2[101] = ""; gets(str1); gets(str2); char *str=delete_char(str1,str2); printf("%s",str); return 0; }
#include <stdio.h>
#include <string.h>
int main() {
char s1[100] = {0};
gets(s1);
char s2[100] = { 0 };
scanf("%s",s2);
int sz = strlen(s1);
char* p1 = s1;
char* p2 = s2;
while (*p2 != '\0')
{
for (int i = 0; i < sz; i++)
{
if (*(p1 + i) == *p2)
{
for (int j = i; j < sz - 1; j++)
{
*(p1 + j) = *(p1 + j + 1);
}
sz--;
}
}
p2++;
p1 = s1;
}
for (int i = 0; i < sz; i++)
{
printf("%c", s1[i]);
}
return 0;
} 要注意的是 string 字符串调用 erase() 函数后迭代器会失效,要将迭代器指针前移一个位置,即执行 --it; 操作。
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main()
{
string str1, str2;
getline(cin, str1);
getline(cin, str2);
unordered_map<char, bool> mp;
for (char c : str2) mp[c] = true;
for (auto it = str1.begin(); it != str1.end(); ++it)
if (mp[*it])
{
str1.erase(it);
--it;
}
cout << str1 << endl;
return 0;
}