Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing lots of string concatenation in C?

I'm porting some code from Java to C, and so far things have gone well.

However, I have a particular function in Java that makes liberal use of StringBuilder, like this:

StringBuilder result = new StringBuilder();
// .. build string out of variable-length data
for (SolObject object : this) {
    result.append(object.toString());
}
// .. some parts are conditional
if (freezeCount < 0) result.append("]");
else result.append(")");

I realize SO is not a code translation service, but I'm not asking for anyone to translate the above code.

I'm wondering how to efficiently perform this type of mass string concatenation in C. It's mostly small strings, but each is determined by a condition, so I can't combine them into a simple sprintf call.

How can I reliably do this type of string concatenation?

like image 943
Alexis King Avatar asked Jan 10 '13 23:01

Alexis King


1 Answers

A rather "clever" way to conver a number of "objects" to string is:

 char buffer[100];
 char *str = buffer;
 str += sprintf(str, "%06d", 123);
 str += sprintf(str, "%s=%5.2f", "x", 1.234567);

This is fairly efficient, since sprintf returns the length of the string copied, so we can "move" str forward by the return value, and keep filling in.

Of course, if there are true Java Objects, then you'll need to figure out how to make a Java style ToString function into "%somethign" in C's printf family.

like image 187
Mats Petersson Avatar answered Sep 24 '22 11:09

Mats Petersson