将2D数组转换为char *数组并将char复制到字符串末尾的最快方法 [英] Fastest way to convert 2D-array into char* array and copy a char into end of string
问题描述
我正在寻找示例代码或如何改进以下代码(这是非常慢的IMO,但我可以编写),以最快的方式将2D数组转换为char*
并复制char
.
I'm looking for an example code or how to improve the below code (that it's very slow IMO, but it's that I can write) to the fastest way to convert an 2D-array into a char*
and copy a char
to it.
char*
join(int c, size_t arrsize, const char* arr[])
{
char *buf, *tbuf, *val;
size_t i, vsize, total;
buf = malloc(1);
for(i = total = 0; i < arrsize; ++i) {
val = arr[i];
vsize = strlen(val);
if((tbuf = realloc(buf, total + vsize + 2)) == NULL) {
if(buf != NULL)
free(buf);
return NULL;
}
buf = tbuf;
memcpy(buf + total, val, vsize);
total += vsize;
buf[total] = c;
total += 1;
}
buf[total] = '\0';
return buf;
}
通话
const char *foo[] = { "a", "b", "c"};
char *baa = join(' ', 2, foo); //a b c
if(baa) {
printf("%s\n", baa);
free(baa);
} else {
printf("No memory\n");
}
如何优化?
推荐答案
我同意Shawn的观点,单个malloc调用可能更有利.当他发布答案时,我正在为您的代码编写自己的看法:
I agree with the Shawn, a single malloc call is probably more advantageous. I was writing up my own take on your code while he was posting his answer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* join(char delimiter, size_t arrsize, const char* arr[]) {
size_t i;
size_t total;
char* joined;
for (i = total = 0; i < arrsize; i++) {
if (arr[i] != NULL)
total += strlen(arr[i]) + 1; // size of c-style string + delimiter
}
// Note that last delimiter will actually be null termination
joined = (char*)malloc(sizeof(char) * total);
if (joined != NULL) {
// first character isn't guaranteed to be null termination
// set it so strcat works as intended, just in case
joined[0] = '\0';
for (i = 0; i < arrsize; i++) {
if (arr[i] != NULL) {
strcat(joined, arr[i]);
if ((i + 1) != arrsize)
strncat(joined, &delimiter, 1);
}
}
return joined;
}
int main(int argc, char** argv) {
const char* foo[] = { "aasdasd", "bgsfsdf", "asdasisc" };
char* baa = join(' ', 3, foo);
if (baa != NULL) {
printf("%s\n", baa);
free(baa);
} else {
printf("No memory\n");
}
return 0;
}
我根据您想完成的内容进行了一些更改,join的第一个参数是用于分隔组合字符串的字符定界符,第二个是arr中的字符串数,第三个显然是数组
I made some changes depending on what I thought you were trying to accomplish, the first argument to join is the character delimiter used to separate combined strings, the second is the number of string in arr, and the third is obviously the array.
代码应编译并运行,并添加"assdasd bgsfsdf asdasisc",即填充数组以测试:P时我在键盘上混搭的内容:
The code should compile and run, yeilding "assdasd bgsfsdf asdasisc", that is, what I mashed on my keyboard when populating the array to test :P
这篇关于将2D数组转换为char *数组并将char复制到字符串末尾的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!