Judging by insertable's comments, (s?) he's trying to get this code working... So let me offer my take...
As with the others, I'm presuming each word is delimited by a single ",". If you can have multiple character delimiters, you'll need to add a second find (i.e. find_first_not_of) to find the start/end of each word.
And yes, you could insert the '@' characters into the preexisting string. But inserting for each word gets a little inefficient (O(N^2)) unless you're clever. That sort of cleverness usually comes with a high maintenance/debugging cost. So I'll just stick to using two strings...
(There ought to be some brilliant way to do this with STL algorithms. But I'm sick and I just don't see how to accommodate insertion right now...)
References: C++-strings C++-strings STL count_if
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define SHOW(X) cout << # X " = " << (X) << endl
int main()
{
// 0123456789_123456789_1234
string inString(",llama,goat,cow,,dog,cat");
string outString;
/* This code assumes inString.size() > 0 */
const iterator_traits<string::iterator>::difference_type numberOfWords
= count_if( inString.begin(), inString.end(),
bind2nd( equal_to<char>(), ',' ) )
+ 1;
string::size_type startIndex, endIndex;
outString.reserve( inString.length() + numberOfWords );
for ( startIndex = endIndex = 0;
endIndex != string::npos;
startIndex = endIndex + 1 )
{
outString += "@";
/* No startIndex+1 here. We set startIndex=endIndex+1 in the for loop */
endIndex = inString . find_first_of( ",", startIndex );
outString . append ( inString, startIndex,
( (endIndex == string::npos)
? string::npos : endIndex - startIndex + 1) );
}
SHOW( numberOfWords );
SHOW( inString );
SHOW( outString );
SHOW( inString.size() );
SHOW( outString.size() );
SHOW( inString.capacity() );
SHOW( outString.capacity() );
}