如何连接在C 2字符串? [英] How to concatenate 2 strings in C?

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

问题描述

如何添加2字符串?

我试过 NAME =DERP+HERP; ,但我得到了一个错误

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

防爆pression必须有整数或枚举类型

推荐答案

C没有对其他一些语言有弦的支持。 C中的一个字符串就是一个指向字符的数组由第一个空字符终止。在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(char *s1, char *s2)
{
    char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-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(char *s1, char *s2)
{
    size_t len1 = strlen(s1);
    size_t len2 = strlen(s2);
    char *result = malloc(len1+len2+1);//+1 for the zero-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 2字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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