![](/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.