如何在C中连接两个字符串? [英] How do I concatenate two strings in C?

查看:44
本文介绍了如何在C中连接两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何添加两个字符串?

我尝试了 name ="derp" +"herp"; ,但出现错误:

I tried name = "derp" + "herp";, but I got an error:

表达式必须具有整数或枚举类型

Expression must have integral or enum type

推荐答案

C不支持某些其他语言提供的字符串.C中的字符串只是指向以第一个空字符终止的 char 数组的指针.C中没有字符串连接运算符.

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

使用 strcat 连接两个字符串.您可以使用以下功能来做到这一点:

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

这不是最快的方法,但是您现在不必为此担心.请注意,该函数将堆分配的内存块返回给调用方,并传递对该内存的所有权.当不再需要内存时,调用者有责任释放.

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

像这样调用函数:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

如果确实碰巧受到性能的困扰,那么您将希望避免重复扫描输入缓冲区以寻找空终止符.

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

如果您打算对字符串进行大量处理,那么最好使用对字符串具有一流支持的另一种语言.

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

这篇关于如何在C中连接两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆