![](/img/trans.png)
[英]Copy a single character from a character array to another character array in C
[英]How to copy a character array into another character array in 'c' using pointers and without using string library
如何使用指针和不使用字符串库将字符数组复制到C
另一个字符数组?
我试过这个:
头文件:
char strconcat(char a[100], char b[100]) {
int i=0,j=0;
while(a[i] != '\0'){
i++;
}
while(b[j] != '\0'){
a[i] = b[j];
j++;
i++;
}
return a[100];
}
char *strconcat(char *dst, const char *src)
{
char *bak = dst;
while (*dst) dst++;
while (*dst = *src)
{
dst++;
src++;
}
return bak;
}
请注意,您不能将char a[100]
作为函数参数。 在C中,这种表示法自动转换为char a[]
,相当于char *a
。
您也不必将事物与0进行比较。省略比较将使默认情况发生。
void strconcat(char *a, char *b)
{
int i=0,j=0;
while(a[i++]!='\0')
;
while(b[j]!='\0')
a[i++]=b[j++];
a[i] = '\0';
}
第一个版本天真地假设目的地有足够的空间,
char *
my_strcat(char *destp, char *srcp)
{
if(!destp) return(destp); //check that dest is valid
if(!srcp) return(destp); //check that src is valid
char *dp=destp; //save original destp
while(*dp) { dp++; } //find end of destp
while(*srcp)
{
*dp++ = *srcp++; //copy src to dest, then increment
}
return(destp);
}
第二个版本允许您指定目标的最大大小,
char *
my_strncat(char *destp, char *srcp, long max)
{
if(!destp) return(destp); //check that dest is valid
if(!srcp) return(destp); //check that src is valid
char *dp=destp; //save original destp
long x=0;
while(*dp && (x<max)) { dp++; ++x; } //find end of destp
while(*srcp && (x<max)) //copy from src while more space in dst
{
*dp++ = *srcp++; ++x; //copy src to dest, then increment
}
*dp = '\0'; //ensure destination null terminated
return(destp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.