CopyPastehas never been so tasty!

Reverse and Replace string in C#

by anonymous

  • 0
  • 0
  • 0
104 views

Reverse and Replace string in C#

To invoke multiple methods in a program, we will use a delegate which is defined below.DelegateA delegate is a reference type that defines a method signature. It holds one or more methods which can be static and non-static and can return a value. It can hold and invoke multiple methods and the methods are invoked sequentially in the order in which they are added.String.Replace methodString.Replace method is used to do some effective change in string. It replaces all occurrence of one substring into another desired substring.To reverse a string we will define a new method which will work in a loop and will reverse the string. The following sample code will show the reversing and replacing of string. In this sample code we use a delegate which is a reference type and will use to invoke multiple methods. String.replace() is used to replace spaces with commas. ReverseString() works in loop which will take the entire string and will reverse it. E.g, if the string is “he is a boy” then the resulting string will be “boy a is he”. Code

delegate void Delegate(ref string str);

    class Program

    {

        static void ReplaceSpaces(ref string s)

        {

            Console.WriteLine("Replaces spaces with Commas.");

            s = s.Replace(' ', ',');

        }

        static void ReverseString(ref string r)

        {

            string temp = "";

            int i, j;

            Console.WriteLine("Reversing string.");

            for (j = 0, i = r.Length - 1; i >= 0; i--, j++)

                temp += r[i];

            r = temp;

        }

        public static void Main()

        {

            Delegate DE;

            Delegate replaceSpace = new Delegate(ReplaceSpaces);

            Delegate reverseStr = new Delegate(ReverseString);

            string str = "I Have A Pet Dog";

            DE = replaceSpace;

            DE(ref str);

            Console.WriteLine("Resulting string: " + str);

            Console.WriteLine();

 

            // resetting string

            str = "I Have A Pet Dog";

            DE = reverseStr;

            DE(ref str);

            Console.WriteLine("Resulting string: " + str);

            Console.ReadLine();

        }

    }

Add A Comment: