Judging by the inserted comments, (s?) It is trying to get this code to work ... So let me suggest my trick ...
Like others, I assume that each word is limited to one ",". If you can have multiple character delimiters, you need to add a second search (e.g. find_first_not_of) to find the beginning / end of each word.
And yes, you can insert the characters '@' into an existing line. But inserting for each word becomes a little ineffective (O (N ^ 2)) if you are not smart. Such a mind usually comes with a high maintenance / debugging cost. So I will just stick to two lines ...
(There must be some brilliant way to do this using STL algorithms, but I'm sick and I just don't understand how to place the insert right now ...)
References: C ++ - C ++ strings - STL count_if strings
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define SHOW(X) cout << # X " = " << (X) << endl
int main()
{
string inString(",llama,goat,cow,,dog,cat");
string outString;
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 += "@";
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() );
}
source
share