c-sharp
  1. c-sharp-program-to-copy-string-without-using-strcpy

Program to Copy String Without Using strcpy() - (C# Basic Programs)

Copying a string is a common operation in programming, but the standard function strcpy() is not always available. In this tutorial, we will discuss a program to copy a string without using the strcpy() function in C# programming language.

Syntax

The syntax for copying a string without strcpy() in C# is as follows:

char[] source = "string to copy".ToCharArray();
char[] destination = new char[source.Length];
for (int i = 0; i < source.Length; i++) {
    destination[i] = source[i];
}

Example

using System;

class Program {
    static void Main(string[] args) {
        string source = "Hello world!";
        char[] destination = new char[source.Length];

        for (int i = 0; i < source.Length; i++) {
            destination[i] = source[i];
        }

        Console.WriteLine("Source string: " + source);
        Console.WriteLine("Destination string: " + new string(destination));
    }
}

Output:

Source string: Hello world!
Destination string: Hello world!

Explanation

The approach we took in this program is to create two character arrays - one for the source string and one for the destination string. We then loop through the source character array and copy each character to the destination character array. Finally, we use the new string() constructor to turn the destination character array back into a string.

Use

Copy string without strcpy() program in C# is useful when the strcpy() function is not available, or you want to avoid using it for security reasons.

Summary

In this tutorial, we have discussed a program to copy a string without using the strcpy() function in C# programming language. We have seen the syntax, example, explanation, use, and benefits of copying a string without strcpy() in C#. This program shows that we can achieve the same functionality of strcpy() without using the function.

Published on: