开发者

Insert a string into another string efficiently

开发者 https://www.devze.com 2023-01-26 00:17 出处:网络
I have char aa[] = { \"Hello, !\" }; char bb[] = { \"World\" }; How to insert b开发者_开发百科b into aa the most efficiently with cstring ?

I have

char aa[] = { "Hello, !" };

char bb[] = { "World" };

How to insert b开发者_开发百科b into aa the most efficiently with cstring ?


  • allocate big enough buffer (malloc/new[])
  • copy the first part of the aa string into the buffer (strncpy/memcpy)
  • copy the bb string (strcpy/memcpy)
  • copy the rest of the aa string (strncpy/memcpy)


Maximum optimization usually requires taking advantage of the specific requirements. You make the code less general to gain speed (or some other metric). You may know some corner you can cut, while we have to guess.

Code fragments below use these headers:

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

If you want to maximize performance, it would help to pre-allocate enough space for the final string, post- insert:

#define MAX_STR_LEN 256 

char aa[MAX_STR_LEN] = "Hello, !";
char bb[] = "World";

You don’t indicate how you know where to insert. For my sample code I define the insert point as an offset into the destination string:

size_t pos = 7;

If you know either of the string lengths in advance you should use a const instead of calling strlen, which has to scan the string. Here I don’t’ assume you’re that lucky.

size_t srclen = strlen(bb);

The memmove function properly handles overlapping source and destination:

//  +1 for count to include terminating null
memmove(aa+pos+srclen, aa+pos, strlen(aa)-pos+1);

memcpy is faster on some platforms and can be safely used to copy between strings:

memcpy(aa+pos, bb, srclen);

Now aa contains the result.

If you can’t pre-allocate aa to the required size, then:

// additional include for malloc
#include <stdlib.h>

char aa[] = "Hello, !";
char bb[] = "World";
size_t pos = 7;    

size_t srclen = strlen(bb);
size_t dstlen = strlen(aa);
char *m = malloc(srclen+dstlen+1);
// Test for NULL or use an allocator that throws

memcpy(m, aa, pos);
memcpy(m+pos, bb, srclen);
memcpy(m+pos+srclen, aa+pos, dstlen-pos+1);

m contains the result and probably needs to be free'd eventually.

Remember if there is any chance for buffer overflow, you have to check lengths to avoid memory corruption and a possible security vulnerability.

I hope this helps.


std::string aa = "Hello, !";
std::string bb = "World";
aa.insert(7, bb);

dont wanna use string from C++

Then why are you tagging this as C++?


char *newStr = malloc(strlen(aa) + strlen(bb));

sprintf(newStr, "%s%s", aa, bb);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号