# fast string concat, any ideas?

This is a discussion on fast string concat, any ideas? within the C++ Programming forums, part of the General Programming Boards category; Hi, lets say i have a number like 9152 ...and its to be expanded as such : 11111111122222 (thats 9 ...

1. ## fast string concat, any ideas?

Hi, lets say i have a number like 9152 ...and its to be expanded as such : 11111111122222
(thats 9 ones and 5 twos)

so .. if i want to expand any given number ... the obvious quick solution is something like this..

Code:
```string expand(string& input)
{
string ret="";
for(int i=0;i<input.length();i+=2)
{
int expand_amount = input[i] - '0';
for(int j=0;j < expand_amount; ++j)
ret+=input[i+1];
}
return ret;
}```
but in this solution ... we do ret.length() string concats , I want to assume that this is horrible for inputs such as 9999999999.

Anyone have a solution to making this a bit more .....clever?

(probably avoiding string concats all together)

2. String has an append() method that can append any number of a certain character.

3. Add up the 1st, 3rd, ..... (input.length()-1)th values before starting. That sum will be related to the final length of ret.

Incidentally, what do you expect the function to do if input.length() is an odd value?

4. Originally Posted by whiteflags
String has an append() method that can append any number of a certain character.
ah cool, that seems like the tool that would suit this, i think

Add up the 1st, 3rd, ..... (input.length()-1)th values before starting. That sum will be related to the final length of ret.

Incidentally, what do you expect the function to do if input.length() is an odd value?
nah, odd lengths are invalid..

and yea thats an idea too ,adding up all the odd index numbers in the string.....I misread your post the first time and it actually led me to another idea. (now probably useless since someone mentioned append())

just using a loop containing ret+=ret; , doubling what I have each step, that way the number of string concats would only have been less than 2*log( result.length() )

Popular pages Recent additions