Prepending to a string

35,998

Solution 1

Copying can hardly be avoided if you want it in the same memory chunk. If the allocated chunk is large enough you could use memmove to shift the original string by the length of what you want to prepend and then copy that one into the beginning, but I doubt this is less "clunky". It would however save you extra memory (again, granted that the original chunk has enough free space for them both).

Something like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void prepend(char* s, const char* t);

/* Prepends t into s. Assumes s has enough space allocated
** for the combined string.
*/
void prepend(char* s, const char* t)
{
    size_t len = strlen(t);
    memmove(s + len, s, strlen(s) + 1);
    memcpy(s, t, len);
}

int main()
{
    char* s = malloc(100);
    strcpy(s, "file");
    prepend(s, "dir/");

    printf("%s\n", s);
    return 0;
}

Solution 2

If you don't need the string to be stored in order, but only appear to be in order, then use a thing called a "rope." (It's made of lots of "string", see.)

I believe it's basically a vector (in C terms, an array) of struct { char *begin; char *end };

In C++ it implements all the std::string functions. In C you'd need to write (or get a library of) replacement functions for all the strxxx() functions.

What the "rope" would do to prepend a string to another string is simply insert a new begin,end pair pointing at the new piece of string. It might also have to copy the new piece of string, if it's a temporary pointer. Or it can just take ownership of the string if it's an allocated string.

A rope is very good for large strings. But anything under about 8 KB is faster to handle with memmove and memcpy.

Solution 3

sprintf() is generally not 'fast'. Since you know it's pre-pending memmove() twice would probably be preferable for speed.

If you're allocating the strings with malloc() originally you might consider using realloc() to resize the character arrays so they can contain the new string.

   char* p = malloc( size_of_first_string );
   ...
   p = realloc( p, size_of_first_string + size_of_prepended_string + 1 );
   memmove( p + size_of_prepended_string, p, size_of_first_string );
   memmove( p, prepended_string, size_of_prepended_string );

Solution 4

Perhaps I'm confused, but I believe that a prepend is the same as appending with the strings swapped. So instead of prepending "Hello" to "World", the string "World" can be appended to "Hello":

const char world[] = "World";
const char hello[] = "Hello";

// Prepend hello to world:
const unsigned int RESULT_SIZE = sizeof(world) + sizeof(hello) + 2 * sizeof('\0');
char * result = malloc(RESULT_SIZE);
if (result)
{
  strcpy(result, hello);
  strcat(result, world);
  puts("Result of prepending hello to world: ");
  puts(result);
  puts("\n");
}

Also, the main waste of execution time is finding the end of a string. If the strings were stored with the length, the end could be calculated faster.

Solution 5

You can climb to the top of the directory tree keeping the names as you go along, then paste the names together all at once. At least then you aren't doing unnecessary copies by pushing onto the front.

int i = 0;
int j;

char temp*[MAX_DIR_DEPTH], file[LENGTH];

while (some_condition) {
    temp[i++] = some_calculation_that_yields_name_of_parent_dir;        
}

char *pCurrent = file;    
for( j = i-1; j > 0; j-- )
{
    strcpy(pCurrent, temp[j]);
    pCurrent += strlen(temp[j]);
    *pCurrent++ = '\';
}
strcpy(pCurrent, filename);
*pCurrent = 0;
Share:
35,998
Ryan
Author by

Ryan

I'm currently a grad student in computer science. My main interests are computer graphics and operating systems. In the past, I've done work in the environmental field on various models. I've also written benchmarks for distributed file systems. Of course, there have been a lot of miscellaneous projects/experiences mixed in. At the moment, I'm trying to learn more about photo-realistic rendering (OpenGL/GLSL) and character animation.

Updated on December 12, 2020

Comments

  • Ryan
    Ryan over 3 years

    What is the most efficient way to prepend to a C string, using as little memory as possible?

    I am trying to reconstruct the path to a file in a large directory tree.

    Here's an idea of what I was doing before:

    char temp[LENGTH], file[LENGTH];
    file = some_file_name;
    
    while (some_condition) {
        parent_dir = some_calculation_that_yields_name_of_parent_dir;
        sprintf(temp, "%s/%s", parent_dir, file);
        strcpy(file, temp);
    }
    

    This seems a bit clunky though.

    Any help would be appreciated. Thanks!