题目描述:
输入两个字符串,从第一个字符串中删除第二个字符串中出现的所有字符。例如:输入"they are students." 与 “aeiou”,则应该输出“thy r stdnts.”
分析:
开辟一个256位的哈希表,记录需要删除的字符,遍历第一个字符串,碰到需要删除的字符,删除(即用后面的字符覆盖)
#include <iostream>
#include<string>
using namespace std;
void DelChars(char* pstrSource, char* pstrDel)
{
if(pstrSource == NULL || pstrDel == NULL)
return;
//建立并初始化哈希表
const int hashLength = 256;
unsigned int hashList[hashLength];
for(int i = 0; i < hashLength; ++i)
{
hashList[i] = 0;
}
char *pch = pstrDel;
while(*pch != '\0')
{
hashList[*pch]++;
pch++;
}
char *pfast = pstrSource;
char *pslow = pstrSource;
while(*pfast != '\0')
{
if(hashList[*pfast] == 0)//没找到要删除的,
{
*pslow = *pfast;
pslow++;
}
pfast++;
}
*pslow = '\0';
}
int main()
{
const int StrMaxLength = 100;
cout<<"Enter your first string:"<<endl;
char strFirst[StrMaxLength];
cin.getline(strFirst,sizeof(strFirst));
cout<<"Enter your second string:"<<endl;
char strSecond[StrMaxLength];
cin.getline(strSecond,sizeof(strSecond));
cout<<"the final string you want is:"<<endl;
DelChars(strFirst,strSecond);
cout<<strFirst<<endl;
return 0;
}