How do I add two strings?
如何添加两个字符串?
I tried name = "derp" + "herp";
, but I got an error:
我尝试了name = "derp" + "herp",但是我犯了一个错误:
Expression must have integral or enum type
表达式必须具有整型或枚举类型
9 个解决方案
#1
112
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.
C不像其他语言那样支持字符串。C中的字符串只是指向第一个空字符终止的char数组的指针。C中没有字符串连接操作符。
Use strcat
to concatenate two strings. You could use the following function to do it:
使用strcat连接两个字符串。你可以用下面的函数来做:
#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.
这不是最快的方法,但是你现在不应该担心这个。注意,该函数将堆分配的内存块返回给调用者,并传递该内存的所有权。当不再需要内存时,调用者有责任释放内存。
Call the function like this:
调用函数如下:
char* s = concat("derp", "herp");//do things with sfree(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.
如果你打算用字符串做大量的工作,那么你最好使用一种不同的语言,它对字符串有一流的支持。
#2
14
#include <stdio.h>int main(){ char name[] = "derp" "herp"; printf("\"%s\"\n", name);//"derpherp" return 0;}
#3
9
David Heffernan explained the issue in his answer, and I wrote the improved code. See below.
David Heffernan在他的回答中解释了这个问题,我写了改进后的代码。见下文。
A generic function
We can write a useful variadic function to concatenate any number of strings:
我们可以编写一个有用的变量函数来连接任意数量的字符串:
#include <stdlib.h> // calloc#include <stdarg.h> // va_*#include <string.h> // strlen, strcpychar* concat(int count, ...){ va_list ap; int i; // Find required length to store merged string int len = 1; // room for NULL va_start(ap, count); for(i=0 ; i<count ; i++) len += strlen(va_arg(ap, char*)); va_end(ap); // Allocate memory to concat strings char *merged = calloc(sizeof(char),len); int null_pos = 0; // Actually concatenate strings va_start(ap, count); for(i=0 ; i<count ; i++) { char *s = va_arg(ap, char*); strcpy(merged+null_pos, s); null_pos += strlen(s); } va_end(ap); return merged;}
Usage
#include <stdio.h> // printfvoid println(char *line){ printf("%s\n", line);}int main(int argc, char* argv[]){ char *str; str = concat(0); println(str); free(str); str = concat(1,"a"); println(str); free(str); str = concat(2,"a","b"); println(str); free(str); str = concat(3,"a","b","c"); println(str); free(str); return 0;}
Output:
输出:
// Empty lineaababc
Clean-up
Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:
注意,当分配的内存变得不需要时,应该释放它,以避免内存泄漏:
char *str = concat(2,"a","b");println(str);free(str);
#4
8
You should use strcat
, or better, strncat
. Google it (the keyword is "concatenating").
你应该使用strcat,或者更好的strncat。谷歌it(关键字是“连接”)。
#5
5
You cannot add string literals like that in C. You have to create a buffer of size of string literal one + string literal two + a byte for null termination character and copy the corresponding literals to that buffer and also make sure that it is null terminated. Or you can use library functions like strcat
.
你不能在c中添加字符串字面量,你必须创建一个字符串字面量的缓冲区,一个字符串字面量为2 +一个字节为空终止字符,并将相应的文字复制到那个缓冲区中,并确保它为空终止。也可以使用strcat之类的库函数。
#6
5
I'll assume you need it for one-off things. I'll assume you're a PC developer.
我假设你需要一次性的东西。我假设你是一个PC开发人员。
Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.
使用堆栈,卢克。使用它无处不在。永远不要使用malloc /免费的小额拨款。
#include <string.h>#include <stdio.h>#define STR_SIZE 10000int main(){ char s1[] = "oppa"; char s2[] = "gangnam"; char s3[] = "style"; { char result[STR_SIZE] = {0}; snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3); printf("%s\n", result); }}
If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.
如果每个字符串10kb都不够的话,那么在大小上增加一个0,不要麻烦了——不管怎样,它们都会在作用域的末尾释放它们的堆栈内存。
#7
3
Without GNU extension:
没有GNU扩展:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { const char str1[] = "First"; const char str2[] = "Second"; char *res; res = malloc(strlen(str1) + strlen(str2) + 1); if (!res) { fprintf(stderr, "malloc() failed: insufficient memory!\n"); return EXIT_FAILURE; } strcpy(res, str1); strcat(res, str2); printf("Result: '%s'\n", res); free(res); return EXIT_SUCCESS;}
Alternatively with GNU extension:
或者与GNU扩展:
#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { const char str1[] = "First"; const char str2[] = "Second"; char *res; if (-1 == asprintf(&res, "%s%s", str1, str2)) { fprintf(stderr, "asprintf() failed: insufficient memory!\n"); return EXIT_FAILURE; } printf("Result: '%s'\n", res); free(res); return EXIT_SUCCESS;}
See malloc, free and asprintf for more details.
更多细节请参见malloc, free和asprintf。
#8
1
#include <string.h>#include <stdio.h>int main(){ int a,l; char str[50],str1[50],str3[100]; printf("\nEnter a string: "); scanf("%s",str); str3[0]='\0'; printf("\nEnter the string which you want to concat with string one: "); scanf("%s",str1); strcat(str3,str); strcat(str3,str1); printf("\nThe string is %s\n",str3);}
#9
0
In C, you don't really have strings, as a generic first-class object. You have to manage them as arrays of characters, which mean that you have to determine how you would like to manage your arrays. One way is to normal variables, e.g. placed on the stack. Another way is to allocate them dynamically using malloc
.
在C语言中,作为一般的一级对象,实际上没有字符串。您必须将它们作为字符数组来管理,这意味着您必须决定如何管理您的数组。一种方法是对常规变量,例如放置在堆栈上。另一种方法是使用malloc动态分配它们。
Once you have that sorted, you can copy the content of one array to another, to concatenate two strings using strcpy
or strcat
.
排序之后,可以将一个数组的内容复制到另一个数组中,使用strcpy或strcat将两个字符串连接起来。
Having said that, C do have the concept of "string literals", which are strings known at compile time. When used, they will be a character array placed in read-only memory. It is, however, possible to concatenate two string literals by writing them next to each other, as in "foo" "bar"
, which will create the string literal "foobar".
话虽如此,C确实有“字符串文字”的概念,即编译时已知的字符串。当使用时,它们将是放置在只读存储器中的字符数组。但是,可以将两个字符串字串在一起,比如在“foo”“bar”中,它将创建字符串字面量“foobar”。
#1
112
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.
C不像其他语言那样支持字符串。C中的字符串只是指向第一个空字符终止的char数组的指针。C中没有字符串连接操作符。
Use strcat
to concatenate two strings. You could use the following function to do it:
使用strcat连接两个字符串。你可以用下面的函数来做:
#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.
这不是最快的方法,但是你现在不应该担心这个。注意,该函数将堆分配的内存块返回给调用者,并传递该内存的所有权。当不再需要内存时,调用者有责任释放内存。
Call the function like this:
调用函数如下:
char* s = concat("derp", "herp");//do things with sfree(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.
如果你打算用字符串做大量的工作,那么你最好使用一种不同的语言,它对字符串有一流的支持。
#2
14
#include <stdio.h>int main(){ char name[] = "derp" "herp"; printf("\"%s\"\n", name);//"derpherp" return 0;}
#3
9
David Heffernan explained the issue in his answer, and I wrote the improved code. See below.
David Heffernan在他的回答中解释了这个问题,我写了改进后的代码。见下文。
A generic function
We can write a useful variadic function to concatenate any number of strings:
我们可以编写一个有用的变量函数来连接任意数量的字符串:
#include <stdlib.h> // calloc#include <stdarg.h> // va_*#include <string.h> // strlen, strcpychar* concat(int count, ...){ va_list ap; int i; // Find required length to store merged string int len = 1; // room for NULL va_start(ap, count); for(i=0 ; i<count ; i++) len += strlen(va_arg(ap, char*)); va_end(ap); // Allocate memory to concat strings char *merged = calloc(sizeof(char),len); int null_pos = 0; // Actually concatenate strings va_start(ap, count); for(i=0 ; i<count ; i++) { char *s = va_arg(ap, char*); strcpy(merged+null_pos, s); null_pos += strlen(s); } va_end(ap); return merged;}
Usage
#include <stdio.h> // printfvoid println(char *line){ printf("%s\n", line);}int main(int argc, char* argv[]){ char *str; str = concat(0); println(str); free(str); str = concat(1,"a"); println(str); free(str); str = concat(2,"a","b"); println(str); free(str); str = concat(3,"a","b","c"); println(str); free(str); return 0;}
Output:
输出:
// Empty lineaababc
Clean-up
Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:
注意,当分配的内存变得不需要时,应该释放它,以避免内存泄漏:
char *str = concat(2,"a","b");println(str);free(str);
#4
8
You should use strcat
, or better, strncat
. Google it (the keyword is "concatenating").
你应该使用strcat,或者更好的strncat。谷歌it(关键字是“连接”)。
#5
5
You cannot add string literals like that in C. You have to create a buffer of size of string literal one + string literal two + a byte for null termination character and copy the corresponding literals to that buffer and also make sure that it is null terminated. Or you can use library functions like strcat
.
你不能在c中添加字符串字面量,你必须创建一个字符串字面量的缓冲区,一个字符串字面量为2 +一个字节为空终止字符,并将相应的文字复制到那个缓冲区中,并确保它为空终止。也可以使用strcat之类的库函数。
#6
5
I'll assume you need it for one-off things. I'll assume you're a PC developer.
我假设你需要一次性的东西。我假设你是一个PC开发人员。
Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.
使用堆栈,卢克。使用它无处不在。永远不要使用malloc /免费的小额拨款。
#include <string.h>#include <stdio.h>#define STR_SIZE 10000int main(){ char s1[] = "oppa"; char s2[] = "gangnam"; char s3[] = "style"; { char result[STR_SIZE] = {0}; snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3); printf("%s\n", result); }}
If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.
如果每个字符串10kb都不够的话,那么在大小上增加一个0,不要麻烦了——不管怎样,它们都会在作用域的末尾释放它们的堆栈内存。
#7
3
Without GNU extension:
没有GNU扩展:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { const char str1[] = "First"; const char str2[] = "Second"; char *res; res = malloc(strlen(str1) + strlen(str2) + 1); if (!res) { fprintf(stderr, "malloc() failed: insufficient memory!\n"); return EXIT_FAILURE; } strcpy(res, str1); strcat(res, str2); printf("Result: '%s'\n", res); free(res); return EXIT_SUCCESS;}
Alternatively with GNU extension:
或者与GNU扩展:
#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) { const char str1[] = "First"; const char str2[] = "Second"; char *res; if (-1 == asprintf(&res, "%s%s", str1, str2)) { fprintf(stderr, "asprintf() failed: insufficient memory!\n"); return EXIT_FAILURE; } printf("Result: '%s'\n", res); free(res); return EXIT_SUCCESS;}
See malloc, free and asprintf for more details.
更多细节请参见malloc, free和asprintf。
#8
1
#include <string.h>#include <stdio.h>int main(){ int a,l; char str[50],str1[50],str3[100]; printf("\nEnter a string: "); scanf("%s",str); str3[0]='\0'; printf("\nEnter the string which you want to concat with string one: "); scanf("%s",str1); strcat(str3,str); strcat(str3,str1); printf("\nThe string is %s\n",str3);}
#9
0
In C, you don't really have strings, as a generic first-class object. You have to manage them as arrays of characters, which mean that you have to determine how you would like to manage your arrays. One way is to normal variables, e.g. placed on the stack. Another way is to allocate them dynamically using malloc
.
在C语言中,作为一般的一级对象,实际上没有字符串。您必须将它们作为字符数组来管理,这意味着您必须决定如何管理您的数组。一种方法是对常规变量,例如放置在堆栈上。另一种方法是使用malloc动态分配它们。
Once you have that sorted, you can copy the content of one array to another, to concatenate two strings using strcpy
or strcat
.
排序之后,可以将一个数组的内容复制到另一个数组中,使用strcpy或strcat将两个字符串连接起来。
Having said that, C do have the concept of "string literals", which are strings known at compile time. When used, they will be a character array placed in read-only memory. It is, however, possible to concatenate two string literals by writing them next to each other, as in "foo" "bar"
, which will create the string literal "foobar".
话虽如此,C确实有“字符串文字”的概念,即编译时已知的字符串。当使用时,它们将是放置在只读存储器中的字符数组。但是,可以将两个字符串字串在一起,比如在“foo”“bar”中,它将创建字符串字面量“foobar”。