在字符串中删除特定的字符 【微软面试100题 第六十三题】

题目要求

  输入两个字符串,从第一个字符串中删除第二个字符串中所有的字符。例如,输入"They are students."和"aeiou",则删除之后的第一个字符串变成了"Thy r stdnts.".

题目分析

  1. 把第二个字符串的所有字符都存入一个set中;

  2. 遍历第一个字符串的每个字符,同时判断是否该字符在set中,如果在就用后面不在set中且靠当前字符最近的字符覆盖它,如果不在就继续遍历。

代码实现

#include <iostream>
#include <set>

using namespace std;

char *ChangeChar(char *ch1,char *ch2);

int main(void)
{
    char ch1[] = "They are students.";
    char ch2[] = "aeiou";
    cout << "ch1 is: " << ch1 << endl;
    cout << "ch2 is: " << ch2 << endl;
    cout << "the result is: ";
    cout << ChangeChar(ch1,ch2) << endl;
    return 0;
}
char *ChangeChar(char *ch1,char *ch2)
{
    if(ch1 == NULL)
        return NULL;
    if(ch2 == NULL)
        return ch1;
    char *i = ch1;
    char *j = ch1;
    multiset<char> hash;
    while(*ch2 != '')
    {
        hash.insert(*ch2);
        ch2++;
    }
    multiset<char>::iterator iter;
    while(*i != '')
    {
        iter = hash.find(*i);
        if(iter == hash.end())
            *j++ = *i++;
        else
            i++;
    }
    *j = '';
    return ch1;
}

    

原文地址:https://www.cnblogs.com/tractorman/p/4103348.html