Prepending to a string

后端 未结 8 2115
北荒
北荒 2020-12-09 01:49

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.

8条回答
  •  醉酒成梦
    2020-12-09 02:45

    I leave a buffer at left and at right of the array. You have to hold two index but if you have to do it a lot of times (otherweise there would be no problem for efficency) it worts it. The two index I suggest to be ]s;e], one included and one not:

     #define BUFSIZE 256
     #define LEFTBUF 20
     struct mstring
     {
       char * string;
       unsigned s;
       unsigned e;
      }
      void checkbuf(struct mstring *value, int newstringlen, char   leftorright)
      {
      //have fun here
      }
      char * concat (struct mstring * value, char * str)
      {
           checkbuf(value, strlen(value,str), 'r');
           int i=0;
           while (str[i])
                value->string[value->e++]=str[i++];
       }
       char * set(struct mstring * value, char * str)
       {
            value->e=LEFTBUF;
            value->s=LEFTBUF;
            concat( value,str);
    
       }
    
      char * prepend (struct mstring * value, char * str)
      {
           checkbuf(value, strlen(value,str), 'l');
           int i=strlen(value,str)-1;
           while (i>=0)
                value->string[--value->s]=str[i--];
       }
      int main()
      {
          struct mstring * mystring= (struct mstring *) malloc(sizeof(struct mstring) );
          mystring->string=(char*)malloc(sizeof(char)*BUFSIZE);
          set( mystring,"World");
          prepend(mystring,"Hallo")
    
      }
    

    then you have to prepare a function for fill substrings...

提交回复
热议问题