本文介绍了用C连接字符串,哪种方法更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这两种方法来连接字符串:

I came across these two methods to concatenate strings:

公共部分:

char* first= "First";
char* second = "Second";
char* both = malloc(strlen(first) + strlen(second) + 2);

方法1:

strcpy(both, first);
strcat(both, " ");
strcat(both, second);

方法2:

sprintf("%s %s", first, second);

在这两种情况下的内容两个第一第二

In both cases the content of both would be "First Second".

我想知道哪一个是更有效的(我要执行几个串联操作),或者如果你知道一个更好的方式来做到这一点。

I would like to know which one is more efficient (I have to perform several concatenation operations), or if you know a better way to do it.

感谢您的时间。

编辑:在第一种情况的空间本来的字符串之一内

推荐答案

有关可读性,我会去用

char * s = malloc(snprintf(NULL, 0, "%s %s", first, second) + 1);
sprintf(s, "%s %s", first, second);

如果您的平台支持GNU扩展,你也可以使用 asprintf()

If your platform supports GNU extensions, you could also use asprintf():

char * s = NULL;
asprintf(&s, "%s %s", first, second);

如果你坚持与MS C运行时,你必须使用 _scprintf()来确定最终的字符串的长度:

If you're stuck with the MS C Runtime, you have to use _scprintf() to determine the length of the resulting string:

char * s = malloc(_scprintf("%s %s", first, second) + 1);
sprintf(s, "%s %s", first, second);

下面将最有可能是最快的解决方法:

The following will most likely be the fastest solution:

size_t len1 = strlen(first);
size_t len2 = strlen(second);

char * s = malloc(len1 + len2 + 2);
memcpy(s, first, len1);
s[len1] = ' ';
memcpy(s + len1 + 1, second, len2 + 1); // includes terminating null

这篇关于用C连接字符串,哪种方法更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:58