如何创建自己的strcpy函数?

时间:2013-10-28 17:31:17

标签: string cstring strcmp strlen strncpy

我正在尝试设计一个程序,在其中我将创建一个类似于c标准库(strlen,strcmp,strcpy)中的函数的3个函数。前两个我已经接近完成,只有最后一个是主要问题。我正在尝试创建一个与标准函数strcpy具有相同功能的函数。这是我到目前为止所拥有的。

void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' ; i++) {

    count++;
    }
}

到目前为止,我已经获得了“source”的长度并将其存储在“count”中。我需要采取的下一步是什么?如果可能的话,我宁愿使用另一个for循环和if语句。谢谢!

** * * 修改 ****

这就是我现在所拥有的......

void myStrncpy(char destination[], const char source[], int count) {

    for (int i = 0 ; source[i] != '\0' && destination[i] != '\0' ; i++) {
    destination[i] = source[i];
    count++;
    }

}

输出:

str1 before: stringone
str2 before: stringtwo

str1 after : stringtwo
str2 after : string two

2ND RUN(我在哪里遇到问题):

str1 before: stringthree
str2 before: stringfour

str1 after: stringfoure
str2 after: stringfour

我还需要在代码中添加什么内容,以便复制每个字母,直到它用完房间,或者复制每个字母,直到它用完要复制的字母为止?

3 个答案:

答案 0 :(得分:1)

如果你已经写过MyStrcpy,那你差不多完成了:

  

stpncpy()和strncpy()函数最多复制n个字符   s2进入s1。如果s2小于n个字符长,则s1的余数   用'\ 0'字符填充。否则,s1不会被终止。

所以你有一份strcpy副本,它会在复制n个字符后停止;如果它早于那个停止(b / c你到了s2的结尾),填写剩下的s1 w / / 0。

答案 1 :(得分:1)

/* Include header files
 */

 #include <stdio.h>

/* Pre=processor Directives
 */

 #define word_size   20

/* Function prototype
 */

void my_func_strcpy(char *source, char* destination);


 int main()

 {

        char source[word_size]      = "I am source";
        char destination[word_size] = "I am destination"; 

        printf("The source is '%s' \n", source);
        printf("The destination is '%s' \n", destination);

        /* Calling our own made strcpy function
         */
        my_func_strcpy(source, destination);

        printf("The source data now is '%s' \n");
        printf("The destination data now is '%s' \n");
 }

 /* Function to copy data from destination to source
  */  
 void my_func_strcpy(char *source, char* destination)
 {
    char temp[word_size] = {'\0'};
    int  index    = 0;

    /* Copying the destination data to source data
     */
    while (destination[index] != '\0')
    {
        source[index] = destination[index];
        index++;
    }

    /* Making the rest of the characters null ('\0') 
     */
    for (index = 0; index < word_size; index++)
    {
        source[index] = '\0';
    }
 }

答案 2 :(得分:-1)

/* body of the function*/
/*Mahmoud Mohamed Younis*/
int i;
int j = 0;
for(i=0;i<10;i++)
{
    if(s1[i] == '\0')
    {
      int  index = i;
        while(s2[j]!='\0')
        {
            if(index>10)
               break;
            s1[index] = s2[j];
            j++;
            index++;
        }
        s1[index] = '\0';
        break;
    }
}