简体   繁体   English

在不使用内置 strcpy 的情况下实现 strcpy 函数

[英]Implementing strcpy function without using in-built strcpy

EDIT: The issue is solved and I am very thankful to everyone who helped me, and if you are seeing this post in the future, here's the working code to implement strcpy function in C:编辑:问题已解决,我非常感谢所有帮助过我的人,如果您将来看到这篇文章,这里是在 C 中实现 strcpy函数的工作代码:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
        if(a[i+1] == '\0')
            b[i+1]='\0';
    }
}
int main()
{
    printf("Enter the string: ");
    char a[10];
    scanf("%s",&a);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter the string: helloworld
Input string: helloworld 
Output string: helloworld



Question begins here:问题从这里开始:

I am trying to implement a strcpy function without using inbuilt function.我正在尝试在不使用内置函数的情况下实现 strcpy 函数。 I have searched online but I only found the programs to do this task but not functions .我在网上搜索过,但我只找到了执行此任务的程序,但没有找到功能

I tried various approaches but no luck.我尝试了各种方法,但没有运气。 At the end (Try 4) , I wrote a code that works but I dont understand why the hell is that thing working but previous approaches aren't最后(尝试 4),我写了一个有效的代码,但我不明白为什么这东西有效,但以前的方法却没有

Just looking for a function that can copy value of one string into another when called from main() and displays correct value in output string.只是寻找一个函数,它可以在从 main() 调用时将一个字符串的值复制到另一个字符串中,并在输出字符串中显示正确的值。 I would be really thankful if I could get that.如果我能得到它,我将非常感激。 And ofcourse, I cant use the inbuilt function because I am forced to do this cuz of an exam on Monday where we will have to implement any of the random 7 string functions and explain the code too..当然,我不能使用内置函数,因为我被迫在星期一进行考试,因为我们必须实现随机 7 个字符串函数中的任何一个并解释代码。

EDIT: Also found this https://www.programmersought.com/article/29163684184/ code to implement the same thing but it is written in C++.编辑:还发现这个https://www.programmersought.com/article/29163684184/代码来实现同样的事情,但它是用 C++ 编写的。 Why does schools/colleges still teach C after the invention of C++?为什么在 C++ 发明之后学校/学院仍然教授 C? Anyone knows any C++ to C converters?任何人都知道任何 C++ 到 C 转换器?

Try 1:尝试 1:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    char a[10];
    printf("Enter string: ");
    scanf("%s", &a);
    printf("Input string: %s", a);
    char b[(sizeof(a))];
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter string: helloworld
Input string: helloworld
Output string: helloworldhelloworld





Try 2:尝试2:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string size: ");
    scanf("%d",&n);
    char a[n];
    printf("Enter string: ");
    scanf(" %s",&a);
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Ouput:输出:

Enter the string size: 7
Enter string: helloworld
Input string: helloworld  
Output string: helloworldö





Try 3:尝试3:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string size: ");
    scanf("%d",&n);
    n++;
    char a[n];
    printf("Enter string: ");
    // scanf(" %s",&a);
    fgets(a,n,stdin);
    fgets(a,n,stdin);  //need to write twice or it wont work
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter the string size: 5
Enter string: helloworld
Input string: hello  
Output string: hello⌂





Try 4:尝试4:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    int n;
    printf("Enter the string: ");
    scanf("%d",&n);
    n++;
    char a[n];
    scanf(" %s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[n]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter the string: helloworld
Input string: helloworld 
Output string: helloworld





EDIT:编辑:

Trying approach given by a friend in answers:朋友在回答中给出的尝试方法:

Code:代码:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    for (int i = 0; a[i+1] != '\0'; i++)
    {
        b[i] = a[i];
    }
}
int main()
{
    // int n;
    printf("Enter the string: ");
    // scanf("%d",&n);
    // n++;
    char a[10];
    scanf("%s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter the string: helloworld
Input string: helloworld
Output string: helloworl





EDIT 2:编辑2:

Trying do-while loop:尝试 do-while 循环:

Code:代码:

#include <stdio.h>
void strcopy(char *a, char *b)
{
    // for (int i = 0; a[i+1] != '\0'; i++)
    // {
    //     b[i] = a[i];
    // }
    int i=0;
    do{
        b[i]=a[i];
        i++;
    }while(a[i] != '\0');
}
int main()
{
    // int n;
    printf("Enter the string: ");
    // scanf("%d",&n);
    // n++;
    char a[10];
    scanf("%s",&a);
    // printf("Enter string: ");
    // fgets(a,n,stdin);
    // fgets(a,n,stdin);
    printf("Input string: %s", a);
    char b[sizeof(a)]; 
    strcopy(a,b);
    printf("\nOutput string: %s", b);

    return 0;
}

Output:输出:

Enter the string: helloworld Input string: helloworld Output string: helloworldhelloworld输入字符串:helloworld 输入字符串:helloworld 输出字符串:helloworldhelloworld

OP's strcopy() has various problems in trying to mimic the standard library function: OP 的strcopy()在尝试模仿标准库函数时存在各种问题:

char *strcpy(char * restrict s1, const char * restrict s2);

Missing null character in the destination array目标数组中缺少空字符

This is OP 's primary issue.这是 OP 的主要问题。 Somehow a null character must be assigned in the destination.必须以某种方式在目标中分配一个空字符 OP's various codes fail that. OP 的各种代码都没有做到这一点。

Tip: think about copying a string "" which assign only a null character '\\0' to the destination.提示:考虑复制一个字符串""它只为目标分配一个空字符'\\0'

Wrong parameter order错误的参数顺序

The first parameter should be the destination to match strcpy()第一个参数应该是匹配strcpy()的目标

Missing return value缺少返回值

strcpy() returns the original destination pointer. strcpy()返回原始目标指针。

Advanced: Parameters missing restrict/const attributes高级:参数缺少restrict/const属性

Simply use the library function signature above.只需使用上面的库函数签名。

Advanced: Fails for long strings高级:字符串失败

OP's code uses int to index which is insufficient for long strings. OP 的代码使用int来索引这对于字符串是不够的。 Better to use size_t .最好使用size_t

Tip: Add output clarity提示:添加输出清晰度

When printing the result, add sentinel characters like < > and a final '\\n' .打印结果时,添加标记字符,如< >和最后的'\\n'
For debug efforts, make destination string 2x as big.对于调试工作,将目标字符串设为 2 倍大。

// char b[sizeof(a)]; 
char b[sizeof(a) *2]; 
strcopy(a,b);
// printf("\nOutput string: %s", b);
printf("\nOutput string: <%s>\n", b);

OP's asserts this in not a homework coding task, so a candidate solution: OP 在不是家庭作业编码任务中断言这一点,因此候选解决方案:

char *strcpy(char * restrict s1, const char * restrict s2) {
  // Use unsigned char as all str functions behave as if char was unsigned
  // Also need to save s1 for return
  unsigned char *us1 = (unsigned char *)s1;
  const unsigned char *us2 = (const unsigned char *)s2;

  while (*us2) {
    *us1++ = *us2++;
  }

  return s1;
}

In the olden days when K&R was king, we'd tie a onion to our belts, as was the style at the time and do something like在 K&R 为王的过去,我们会在腰带上系一个洋葱,就像当时的风格一样,并做一些类似的事情

void strcopy(char *a, char *b)
{
   while ( *b++ = *a++ ) {}
}

Now I think the old ways are depreciated现在我认为旧的方式已经贬值了

It has been suggested that I explain why this works.有人建议我解释为什么会这样。

*b = *a does the core function of copying of one byte *b = *a做复制一个字节的核心功能

*b++ = *a++ Adding the auto-increments, moves both the pointers to the next locations in memory after the assignment is done *b++ = *a++添加自动增量,在赋值完成后将两个指针移动到内存中的下一个位置

while (*b++ = *a++) {} loops while the byte copied is non-zero. while (*b++ = *a++) {}循环,而复制的字节不为零。 the empty {} is just to complete the syntax of the while statement空的{}只是为了完成while语句的语法

So the while loop will run copying bytes then incrementing both pointers to the next location until the byte copied was zero, being the end of string因此,while 循环将运行复制字节,然后将两个指针递增到下一个位置,直到复制的字节为零,即字符串的结尾

您没有添加终止\\0

All of your implementations have the same essential bug;你所有的实现都有相同的基本错误; "try 4" works only by accident. “try 4”仅在偶然情况下起作用。 The problem is with the loop termination condition in strcopy .问题在于strcopy的循环终止条件。 When you reach the NUL character that ends the source string, you are stopping the loop and not copying it.当您到达结束源字符串的 NUL 字符时,您将停止循环而不是复制它。 This means that the destination string is not ended and printf walks past its end, printing whatever happens to be in memory beyond.这意味着目标字符串没有结束并且printf越过它的末尾,打印任何发生在内存中的内容。 You must instead copy the NUL and then stop the loop.您必须改为复制 NUL ,然后停止循环。

You also have errors in how you allocate memory for the strings a and b -- different in each implementation, but none of them look abstractly correct to me.您在如何为字符串ab分配内存方面也有错误——在每个实现中都不同,但在我看来它们都没有抽象正确。 Talk to your instructor about how to do this correctly, it's one of the most complicated subjects in C and I don't have enough information about what techniques you are allowed to use.与您的讲师讨论如何正确执行此操作,这是 C 中最复杂的主题之一,我没有足够的信息说明您可以使用哪些技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM