[英]C function to return concatenated string
I am attempting to create a function in C to return a string that is the result of concatenating two smaller strings. 我试图在C中创建一个函数以返回字符串,该字符串是串联两个较小的字符串的结果。 My code looks like this:
我的代码如下所示:
const char *concat(char* s1, char* s2){
char ns[strlen(s1) + strlen(s2) + 1];
ns[0] = '\0';
strcpy(ns, s1);
strcpy(ns, s2);
return ns;
}
I understand that the string ns
exists only within the scope of the function and cannot be returned, but a pointer string would not be editable and would defeat the purpose of the function. 我知道字符串
ns
仅存在于函数范围内,无法返回,但是指针字符串将不可编辑,并且会破坏函数的用途。 Is there a better way to do this or is the function fundamentally flawed? 是否有更好的方法可以做到这一点,或者该功能从根本上存在缺陷?
You can use this example, using strcat() is very simple way: 您可以使用此示例,使用strcat()是非常简单的方法:
#include <stdio.h>
#include <string.h>
void concat(char* s1, char* s2, char* ns) {
ns[0] = '\0';
strcpy(ns, s1);
strcat(ns, s2);
}
int main(int argc, char const *argv[])
{
char* s1="hola";
char* s2 =" mundo";
char s3[strlen(s1) + strlen(s2) + 1];
concat(s1, s2, s3);
printf("\n%s",s3);
printf("\n");
return 0;
}
Solved by using malloc()
to create a dynamic string in heap memory: 通过使用
malloc()
在堆内存中创建动态字符串来解决:
const char *concat(char* s1, char* s2){
char *ns = malloc(strlen(s1) + strlen(s2) + 1);
ns[0] = '\0';
strcat(ns, s1);
strcat(ns, s2);
return ns;
}
Make sure to free()
the memory afterwards, though. 不过,请确保稍后
free()
内存。
The C function that concatenates two string is strcat! 连接两个字符串的C函数是strcat!
int main(void)
{
char *s1="Good ";
char *s2="luck";
char ns[12];
strcpy(ns,s1);
strcat(ns,s2);
printf("%s\n",ns);
return 0;
}
You may also use strcat in this way: 您也可以通过以下方式使用strcat:
strcpy(ns,s1);
printf("%s\n", strcat(ns,s2));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.