在c中连接多个字符串的更好方法?

发布于 2024-11-05 09:59:12 字数 250 浏览 1 评论 0原文

除了连续多次调用 strcat() 之外,是否有更好的方法在 c 中将多个字符串连接在一起,如下所示?

char prefix[100] = "";
strcat(prefix, argv[0]);
strcat(prefix, ": ");
strcat(prefix, cmd_argv[0]);
strcat(prefix, ": ");
strcat(prefix, cmd_argv[1]);
perror(prefix);

Is there a better way to concatenate multiple strings together in c other than having multiple calls to strcat() all in a row, like below?

char prefix[100] = "";
strcat(prefix, argv[0]);
strcat(prefix, ": ");
strcat(prefix, cmd_argv[0]);
strcat(prefix, ": ");
strcat(prefix, cmd_argv[1]);
perror(prefix);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

猛虎独行 2024-11-12 09:59:12
sprintf(prefix,"%s: %s: %s",argv[0],cmd_argv[0],cmd_argv[1]);

或者使用 snprintf 来防止缓冲区溢出。

sprintf(prefix,"%s: %s: %s",argv[0],cmd_argv[0],cmd_argv[1]);

Or snprintf to prevent buffer overruns.

如梦初醒的夏天 2024-11-12 09:59:12

snprintf 将是最好且最容易使用的选项,尽管它可能不是“快”。你没有说明你的标准是什么。不过,简单性绝对是这样的:

snprintf(prefix, sizeof(prefix), "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);

snprintf would be the best and easiest to use option, though it may not be "fast". You didn't state what your criteria was. Simplicity is definitely this, though:

snprintf(prefix, sizeof(prefix), "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);
一百个冬季 2024-11-12 09:59:12

我会像其他人建议的那样使用 sprintf() ,但这是为了完整性:

如果您有

char prefix[100] = "";
stpcpy(stpcpy(stpcpy(sptcpy(stpcpy(prefix, argv[0]), ": "),
        cmd_argv[0]), ": "), cmd_argv[1]);
perror(prefix);

的便利之处在于它可以被“链接”,如上所述。此外,由于 stpcpy() 返回指向结果字符串末尾的指针,因此后续 stpcpy() 调用不需要一次又一次地遍历旧数据。因此,它比多个 strcat() 更高效,并且可能比 sprintf() 更高效。 stpcpy() 是 POSIX:2008。

I would use sprintf() like others have suggested, but this is for completeness:

If you have stpcpy(), then you can do:

char prefix[100] = "";
stpcpy(stpcpy(stpcpy(sptcpy(stpcpy(prefix, argv[0]), ": "),
        cmd_argv[0]), ": "), cmd_argv[1]);
perror(prefix);

The convenience with stpcpy() is that it can be "chained", as above. Also, since stpcpy() returns a pointer to the end of the resultant string, subsequent stpcpy() calls don't need to go through the old data again and again. So, it is more efficient than multiple strcat()s and probably more efficient than sprintf(). stpcpy() is POSIX:2008.

氛圍 2024-11-12 09:59:12

我可能会因此而受到批评,但那又怎样呢。可能发生的最糟糕的事情是我会学到一些东西。

我现在并没有真正使用 C,而且我通常不在 C++ 中使用 C 风格的字符串。但我的一个想法是编写一个修改后的 strcpy() 来返回字符串的结尾:

char* my_strcpy(char*dest, const char* src)
{
    while ((*dest = *src++))
        ++dest;
    return dest;
}

现在 Shlemiel 可以随身携带他的水桶:

char prefix[100] = "";
char* bucket = my_strcpy(prefix, argv[0]);
bucket = my_strcpy(bucket, ": ");
bucket = my_strcpy(bucket, cmd_argv[0]);
bucket = my_strcpy(bucket, ": ");
bucket = my_strcpy(bucket, cmd_argv[1]);
perror(prefix);

我还没有测试过这一点。评论?

编辑:删除了不必要的 my_strcat() 函数。而且它与 stpcpy() 相同,后者显然是 2008 年 POSIX 的一部分。请参阅 http://www.manpagez.com/man/3/stpcpy/

I might take a rep hit for this, but what the heck. The worst thing that can happen is I'll learn something.

I don't really use C these days, and I don't typically use C-style strings in C++. But one idea I have is to write a modified strcpy() that returns the end of the string:

char* my_strcpy(char*dest, const char* src)
{
    while ((*dest = *src++))
        ++dest;
    return dest;
}

Now Shlemiel can bring his bucket along with him:

char prefix[100] = "";
char* bucket = my_strcpy(prefix, argv[0]);
bucket = my_strcpy(bucket, ": ");
bucket = my_strcpy(bucket, cmd_argv[0]);
bucket = my_strcpy(bucket, ": ");
bucket = my_strcpy(bucket, cmd_argv[1]);
perror(prefix);

I haven't tested this. Comments?

EDIT: Removed the unnecessary my_strcat() function. Also it turns out to be the same as stpcpy(), which is apparently part of POSIX as of 2008. See http://www.manpagez.com/man/3/stpcpy/.

归属感 2024-11-12 09:59:12

如果您尝试从其他字符串构建字符串(您的示例建议),那么您可以使用 snprintf。

char prefix[100] = "";
snprintf( prefix, sizeof(prefix), "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);

如果您尝试对现有字符串进行串联,但无法使用格式方法,那么您可能会陷入对 strcat 的多次调用,尽管我强烈建议您可能要考虑使用 strncat 相反,并检查以确保没有缓冲区溢出。

If you're trying to build a string from other strings (which your example suggests), then you can use snprintf.

char prefix[100] = "";
snprintf( prefix, sizeof(prefix), "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);

If you're trying to do concatenation of an existing string, where you can't use the format approach, then you're probably stuck with multiple calls to strcat, although I'd strongly suggest that you might want to consider using strncat instead and checking to ensure you don't have buffer overruns.

不及他 2024-11-12 09:59:12

假设您发布的是 char[fixed_size],而不是 char*,您可以使用单个创意宏以类似 cout 的顺序而不是脱节的 printf 样式格式一次性完成所有操作。如果您正在使用嵌入式系统,此方法将允许您省略大型 printf 系列函数,例如 snprintf() (这也可以防止 Dietlibc 抱怨),甚至不需要 malloc() 中的任何函数。

#include <unistd.h> //for write
//note: you should check if offset==sizeof(buf) after use
#define strcpyALL(buf, offset, ...) do{ \
    char *bp=(char*)(buf+offset); /*so we can add to the end of a string*/ \
    const char *s, \
    *a[] = { __VA_ARGS__,NULL}, \
    **ss=a; \
    while((s=*ss++)) \
         while((*s)&&(++offset<(int)sizeof(buf))) \
            *bp++=*s++; \
    if (offset!=sizeof(buf))*bp=0; \
}while(0)

char buf[100];
int len=0;
strcpyALL(buf,len, argv[0],": ", cmd_argv[0],": ",cmd_argv[1]);
if (len==sizeof(buf))write(2,"error\n",6);
else write(1,buf,len); 
  • 注意 1,您可以使用任何输出 char* 的函数,包括用于将整数转换为字符串类型的 itoa() 等非标准函数。
  • 注意 2,如果您正在使用共享库或已经在静态构建的程序中的任何位置使用 printf 样式函数,则不使用 snprintf() (因为使用此方法编译的代码会更大)的唯一原因是,因为它是内联的,不调用任何外部函数,因此它应该相对较快。

Assuming you have a char[fixed_size] as posted, rather than a char*, you can use a single, creative macro to do it all at once with a cout-like ordering rather than the disjointed printf style format. If you are working with embedded systems, this method will allow you to leave out the large printf family of functions like snprintf() (This keeps dietlibc from complaining too) and doesn't even require malloc() or any functions from <string.h>.

#include <unistd.h> //for write
//note: you should check if offset==sizeof(buf) after use
#define strcpyALL(buf, offset, ...) do{ \
    char *bp=(char*)(buf+offset); /*so we can add to the end of a string*/ \
    const char *s, \
    *a[] = { __VA_ARGS__,NULL}, \
    **ss=a; \
    while((s=*ss++)) \
         while((*s)&&(++offset<(int)sizeof(buf))) \
            *bp++=*s++; \
    if (offset!=sizeof(buf))*bp=0; \
}while(0)

char buf[100];
int len=0;
strcpyALL(buf,len, argv[0],": ", cmd_argv[0],": ",cmd_argv[1]);
if (len==sizeof(buf))write(2,"error\n",6);
else write(1,buf,len); 
  • Note 1, you can use any function that outputs a char*, including nonstandard functions like itoa() for converting integers to string types.
  • Note 2, if you are using a shared library or are already using a printf style function anywhere in your statically built program, the only reason not to use snprintf() (since the compiled code would be larger with this method) would be that since it is inlined and doesn't call any external functions, so it should be relatively fast.
执妄 2024-11-12 09:59:12

您可以使用 snprintf 函数

char prefix[100];
snprintf(prefix, 100, "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);

you can use snprintf function

char prefix[100];
snprintf(prefix, 100, "%s: %s: %s", argv[0], cmd_argv[0], cmd_argv[1]);
恍梦境° 2024-11-12 09:59:12

就不能用宏吗?

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

#define a argv[0]
#define b argv[1]
#define c argv[2]
#define strcat1(a,b,c) strcat(prefix, a);\
                       strcat(prefix, ": ");\
                       strcat(prefix, b);\
                       strcat(prefix, ": ");\
                       strcat(prefix, c);\
                       perror(prefix);\



int main(int argc, char *argv[]){
    char prefix[100] = "";
    strcat1(a,b,c);
    return 0;
}

Couldn't you use a Macro.

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

#define a argv[0]
#define b argv[1]
#define c argv[2]
#define strcat1(a,b,c) strcat(prefix, a);\
                       strcat(prefix, ": ");\
                       strcat(prefix, b);\
                       strcat(prefix, ": ");\
                       strcat(prefix, c);\
                       perror(prefix);\



int main(int argc, char *argv[]){
    char prefix[100] = "";
    strcat1(a,b,c);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文