Problem
Write an efficient function in C that deletes characters from a string. Use the prototype
string removeChars( string str, string remove );
where any character existing in remove must be deleted from str. For example, given a str of “Battle of the Vowels: Hawaii vs. Grozny” and a remove of “aeiou”, the function should transform str to “Bttl f th Vwls: Hw vs. Grzny”. Justify any design decisions you make and discuss the efficiency of your solution.
Solution
Set all the elements in your lookup array to false.
Iterate through each character in remove, setting the corresponding value in the lookup array to true.
Iterate through str with a source and destination index, copying each character only if its corresponding value in the lookup array is false
#include <iostream>
#include <hash_map>
#include <string>
using namespace std;
using namespace stdext;
string removeChars(string s, string remove )
{
hash_map<char, bool> h;
typedef pair <char, bool> cb_pair;
hash_map<char, bool>::iterator it;
char c;
for(int i = 0; i < (int)s.length(); i ++){
c = s.at(i);
if(remove.find(c) != string::npos){
h.insert(cb_pair(c, true));
}
else{
h.insert(cb_pair(c, false));
}
}
string ret;
for(int i = 0; i < (int)s.length(); i ++){
c = s.at(i);
it = h.find(c);
if(it != h.end()){
if(it->second != true){
ret.push_back(c);
}
}
}
return ret;
}
int main(int argc, char* argv[])
{
string str_list[5] = {"Hawaii", "Grozny", "hello", "hh", ""};
string remove = "aeiou";
for(int i = 0; i< 5; i++){
cout << str_list[i] << " after remove " << remove << " is " << removeChars(str_list[i], remove) << endl;
}
return 0;
}