String program #9
(Copy
two strings)
Enter string: Imaginationhunt
Using Copy() function
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: False
Equals: True
Using in-build Clone() function
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: True
Equals: True
Using Assignment '=' operator
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: True
Equals: True
The program for the string is written
in C# programming language and will accept a string as input. The logic is to copy
input string to some other variable and also check whether the reference of
input string is equal to the copied string. There are three ways to copy
strings:
1.
Using
in-built function “Copy()”
2.
Using
in-built function “Clone()”
3.
Using
Assignment ‘=’ operator
Let’s find out a simple and easy way
to code the program.
Practical Implementation:
using System;
namespace patternProblem.String
{
class String9 //copy two strings
{
static void Main(string[] args)
{
Console.Write("Enter string: ");
string str1 = Console.ReadLine();
string str2 = string.Empty;
//Method-1: Using in-build Copy() function
Console.WriteLine("\nUsing Copy() function");
str2 = string.Copy(str1);
Console.WriteLine("str1 = {0}", str1);
Console.WriteLine("str2 = {0}", str2);
Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1,
str2));
Console.WriteLine("Equals: {0}", Object.Equals(str1,
str2));
//Method-2: Using in-build Clone() function
Console.WriteLine("\nUsing in-build Clone() function");
str2 = (string)str1.Clone();
Console.WriteLine("str1 = {0}", str1);
Console.WriteLine("str2 = {0}", str2);
Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1,
str2));
Console.WriteLine("Equals: {0}", Object.Equals(str1,
str2));
//Method-3: Using Assignment = operator
Console.WriteLine("\nUsing Assignment '=' operator");
str2 = str1;
Console.WriteLine("str1 = {0}", str1);
Console.WriteLine("str2 = {0}", str2);
Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1,
str2));
Console.WriteLine("Equals: {0}", Object.Equals(str1,
str2));
Console.ReadKey();
}
}
}
Output:
The input
string here is “Imaginationhunt”. So, based on the input, program will copy the
input string to some other variable and we also check whether both the
variables are using the same reference or not. The output is shown below:
Enter string: Imaginationhunt
Using Copy() function
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: False
Equals: True
Using in-build Clone() function
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: True
Equals: True
Using Assignment '=' operator
str1 = Imaginationhunt
str2 = Imaginationhunt
ReferenceEquals: True
Equals: True
Press any key to continue . . .
For any
query, comment us below.
Skip to
Main Table String based program
Keep learning and sharing...
No comments:
Post a Comment