I am trying to write a function that will find any even subsets of characters in a string, and break them in half by inserting an empty space into the string. For example, given the string “AA BBB CCDD”, my string should be converted to “A A BBB CC DD”.
My breakString() function doesn’t seem to work, and I have no idea why. Can anyone help?
void breakString(string &str1)
{
int pos1 = -1;
int pos2 = str1.find_first_of(" ", pos1+1);
while (pos2 != -1)
{
if(((pos2-pos1)-1)%2 == 0)
{
str1.insert((pos2-pos1)/2, 1, ' ');
return;
}
else
{
pos1 = pos2;
pos2 = str1.find_first_of(' ', pos1+1);
}
}
if((str1.size() - pos1)%2 == 1)
str1.insert((str1.length()-pos1)/2, 1, ' ');
return;
}
You say it doesn’t work, but you don’t say how. I can see two immediate
prblems: the first is that you return immediatly when you find the first
word with an even length, so you obviously won’t break any following
words; and the second is that if you do want to continue, the
insertwill have changed the values of any position after it.
(FWIW: I’d probably break the entire string down into words first,
putting them in an
std::vector<std::string>, then iterate on that,inserting the extra space where needed, then reassemble them. It’s
probably a bit slower than the approach you’re using, but it’s a lot
cleaner and easier to follow.)