patterncppMajor
Function for removing forbidden characters
Viewed 0 times
removingfunctionforcharactersforbidden
Problem
void removeForbiddenChar(string* s)
{
string::iterator it;
for (it = s->begin() ; it end() ; ++it){
switch(*it){
case '/':case '\\':case ':':case '?':case '"':case '':case '|':
*it = ' ';
}
}
}I used this function to remove a string that has any of the following character: \, /, :, ?, ", , |. This is for a file's name. This program runs fine. It simply change a character of the string to a blank when the respective character is the forbidden character. However, I have a feeling against this use of switch statement. I simply exploit the case syntax here, but this, somehow nags me. I just don't like it. Anybody else got a better suggestion of a better implementation in this case?
Solution
Declare a string containing the illegal characters:
Your loop should end up looking like this:
It's more maintainable and readable. You can tell if you've duplicated a character quite easily and since you can do it with any target string and any string of illegalChars you've just created for yourself a generic
I may be using those pointers wrong. My C++fu is weak... for now.
"\\/:?"<>|". All you need to do is check if the char is in the array, so use a native function for that, or write a method CharInString(char needle, string haystack) which loops through the contents of the provided haystack to check if the needle is inside it.Your loop should end up looking like this:
string illegalChars = "\\/:?\"<>|"
for (it = s->begin() ; it end() ; ++it){
bool found = illegalChars.find(*it) != string::npos;
if(found){
*it = ' ';
}
}It's more maintainable and readable. You can tell if you've duplicated a character quite easily and since you can do it with any target string and any string of illegalChars you've just created for yourself a generic
RemoveIllegalChars(string targetString, string illegalChars) method usable anywhere in your program.I may be using those pointers wrong. My C++fu is weak... for now.
Code Snippets
string illegalChars = "\\/:?\"<>|"
for (it = s->begin() ; it < s->end() ; ++it){
bool found = illegalChars.find(*it) != string::npos;
if(found){
*it = ' ';
}
}Context
StackExchange Code Review Q#283, answer score: 26
Revisions (0)
No revisions yet.