coding - 在字符串中删除特定的字符

45 篇文章 0 订阅
43 篇文章 0 订阅

题目描述:

输入两个字符串,从第一个字符串中删除第二个字符串中出现的所有字符。例如:输入"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;  
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值