输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”(牛客网)
下面用一副图大致解释一下C语言的解题思路:src:要删除的字符串 ,dest :保存要删除的数据的字符串。
1.外层遍历dest,逐个查找删除。
2.用tmp找到第一次匹配到的位置
3.src串中有,就删,没有继续进入外层循环
4.查找到了,,,,重点在这里,再用一层while循环查找下一个字符是不是要删的那个,直到找到不删的退出while。此处防止出现此例子:src =“haaat” ,dest =“a”
tmp必须找到’t’字符的位置才能往前覆盖。
5.后面的往前面覆盖。
6.src找完了,给最后一个值附上结束符‘\0’(跳出条件是tmp,不再进入了,也就不会给ip1附上“\0”,必须主动加上)。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
void DeleteString_C(char* src, const char* dest)
{
if (!src||!dest)
{
return;
}
char* ip1,*tmp = src;
const char* ip2;
for (ip2 = dest; *ip2; ip2++,tmp = src)//遍历dest,依次在src中查找删除
{
while(*tmp)//找到第一个要删的位置
{
if (*tmp != *ip2)
{
tmp++;
}
else
{
break;
}
}
if (*tmp)//如果要删的字符在src中没有就不删,继续第一个for循环找下一个要删的字符
{
for (ip1 = tmp++; *tmp; ip1++, tmp++)//(ip1=tmp++)tmp要覆盖ip1,所以跳到的下一个位置
{
while (*tmp == *ip2)
//直到找到不是删的那个字符例如:src = "haaat",dest="a";
//就要找到‘t’为止;
{
tmp++;
}
*ip1 = *tmp;//将后面的字符移到前面;
}
*ip1 = '\0';//因为tmp在'\0'位置跳出了,没有给ip1的下一个位置赋字符串结束符
}
}
}
这里解释一下C++的做法:
由于STL库提供了操作字符串的string类,我们就直接用:我这里用了模板函数,无论传string函数char*都可接。
1.构造两个string对象接src 和dest
2.遍历dest在用find函数查找的那个字符(find函数返回值为查找到的坐标,返回-1时说明没找到)
3.找不到就找dest的下一个字符
…找到就erase那个位置的值
4.把构造的string对象的值copy给原串(string 的c_str()函数返回值为const不能直接=,更何况对象最后就析构了)
C++的库用真的是好用,处理问题,简单清晰。
template<class T>
void DeleteString_CPP(T src,const T dest)
{
string src_str(src);
string dest_str(dest);
if (src_str.empty() || dest_str.empty())
{
return;
}
int pos;
string::iterator ip1;
string::iterator src_begin = src_str.begin();//循环内多次调用end函数,这里直接用一个变量存它,减少栈开销
string::const_iterator ip2 = dest_str.begin();
string::const_iterator dest_end = dest_str.end();//循环内多次调用end函数,这里直接用一个变量存它,减少栈开销
for (; ip2 != dest_end; ip2++)
{
do
{
pos = src_str.find(*ip2);//找到dest第一个字符在src中的位置返回(找不到返回-1)
if (pos >= 0)//找到了
{
ip1 = src_begin + pos;//ip1记录要删除字符串位置的迭代器
src_str.erase(ip1);
}
}while (pos >= 0);//src里面可能有重复的待删字符,使用while循环删除至找不到为止(pos = -1)
}
strcpy(src, src_str.c_str());//将string对象的值赋回原串`在这里插入代码片`
}
int main()
{
char src[] = "They are students";
char src2[] = "They are students";
char dest[] = "aeiou"; //输出Thy r stdnts
DeleteString_C(src, dest);
cout << src << endl;
DeleteString_CPP(src2, dest);
cout << src2 << endl;
system("pause");
return 0;
}
-----------------------------------------------------------------------------------------------更新
大佬的想法就是不一样,,,这个大佬不是我啊,哈哈。看见了下面这个解法,感觉自己上面的那两个太LOW了(可能是我理解错题了)。简单介绍一下:
1.找一个字符串str,大小256,为什么呢,因为字符一共就256种。
2.遍历dest,str的坐标对应dest的ASCII码,出现了那个坐标的值就++,否则为0.
3.遍历src,str的坐标对应src的ASCII码,如果那个坐标的值为0,说明不删,就存在res串中。
输出res.
整体感觉不是很难,但是不容易想到,这里使用了哈希表的思想。
void DeleteSameString()
{
string src;
string dest;
getline(cin, src);
getline(cin, dest);
char str[256] = {};
string tmp;
if (src.empty() || dest.empty())
{
return;
}
int i;
for (i = 0; i < dest.size(); i++)
{
str[dest[i]]++;
}
for (i = 0; i < src.size(); i++)
{
if (str[src[i]] == 0)
{
tmp += src[i];
}
}
cout << tmp << endl;
}