I have a question about removing a character from a string and replacing it with something else. I am replacing all lower case singular a's with the string "one". My function is below and the problem I am having is that it will not replace the single letter a if the a starts the string.
If I input:
I eat a cake - it outputs correctly - I eat one cake.
abcd - it outputs correctly - abcd
A man goes to a park - it outputs correctly - A man goes to one park
If I input:
a man likes his car- it outputs the same string without replacing the beginning a.
I am using Visual Studio and when I have tried various loops and if statements in the debugger the position is always -1 and skips the replacement.
string stringOne( string &strln )
{
int position = strln.find( " a");
while( position != string::npos )
{
if( strln.find( " a" ) )
{
strln.replace( position, 3, " one " );
position = strln.find( " a", position + 1 );
}
}
return strln;
}
Pardon my ignorance but what are code tags?
If I take out the space before the " a" then it replaces every a not just the first one. How do I replace just the first a with "one" and leave the other a's in the string unchanged?
Ex.
input: a man likes his car
output: one man likes his car
Thanks
[code]"Put the code inside code tags"[/code]
Perl regex "s/^a | a\.?$| a /one/g" I think it is better to use a special treat for the "a" at the end or the beginning of the string
Perl regex has a nice "word boundary" assertion "\b" such that "\ba\b" will match any "a" that sits by itself, whether at the beginning, end or middle of a line.
With that said, let's get to the practical matter at hand: doing this in C++
One way to deal with this is to walk through the string, finding the first and last letter of the next word in the string. Then check whether that substring matches "a". If it is, replace it. Repeat until you reach the end of the string.
thanks for the help everyone. I got it.
I'm sure its been a while since you guys had to rack your brain for hours to figure out a simple piece of code like this but that's where I am right now and its is a cool feeling to finally get it.
I will have many more question coming soon. If you guys would help a fledgling programmer I would appreciate it.