-
Replacing characters
Hey,
I would like to replace every character in a string that is not a-z A-Z 0-9 or ' with a space. Currently I am trying to approach it this way:
Code:
replace(ss.begin(), ss.end(), '!', ' ');
Which would require dozens of those statements, one for each character that I don't want. Is there anyway to have the program check the string and convert any character that is not a-zA-Z' with a space, instead of writing individual replace statements?
-
Use transform. Write a function that takes a character and returns that character if it is alphanumeric, or ' ' if it is not.
-
So something like this?
Code:
#include <ctype.h>
char checkVal(char x)
{
if(isalnum(x))
return x;
else
return " ";
}
-
>> return " "
That should be return ' ' (use single quotes for characters).
You need to call that in a loop on each character in your string. Using the transform function from <algorithm> can help you do that in one line of code.
-
So if I wanted to convert every character that is not a letter, ', or a space to a space, the code would be:
Code:
string modifyWord(string ss)
{
for(int xx = 0; xx < (int)ss.length(); xx++)
{
ss[xx] = tolower(ss[xx]);
if(!isalpha(ss[xx]) && ss[xx] != ' ' && ss[xx] != "'")
ss[xx] = ' ';
}
return ss;
}
-
Using the transform function as suggested:
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
char checkVal(char x)
{
if(std::isalnum(x))
return x;
else
return ' ';
}
int main()
{
std::string ss("ab$^&cdefg!@123");
std::cout << ss << std::endl;
std::transform(ss.begin(),ss.end(),ss.begin(),checkVal);
std::cout << ss << std::endl;
return 0;
}
Outputs:
Code:
ab$^&cdefg!@123
ab cdefg 123
-
Why didn't you use checkVal in your loop? Instead you used different code that probably doesn't compile and doesn't do the same thing.
-
Ok, thanks. When I was trying it a different way however I came across a compiler error that intrigued me. The error was this:
Code:
18 main.cpp ISO C++ forbids comparison between pointer and integer
And the code:
Code:
for(int xx = 0; xx < (int)ss.length(); xx++)
{
ss[xx] = tolower(ss[xx]);
if(!isalpha(ss[xx]) && ss[xx] != "'")
ss[xx] = ' ';
}
Just the statement if(!isalpha(ss[xx])) worked, but when I added && ss[xx] != " ' " (apostrophe), that error arose.
-
If you need to put the apostrophe character between character marks you need to escape it.
I wouldn't take special measures to prevent a space being replaced with a space.
Code:
if(!isalpha(ss[xx]) && ss[xx] != ' ' && ss[xx] != '\'')
ss[xx] = ' ';