w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Reverse the strings contained in each pair of matching parentheses in a given string

C# Sharp Basic: Exercise-62 with Solution

Write a C# program to reverse the strings contained in each pair of matching parentheses in a given string and also remove the parentheses within the given string.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;
using System.Collections;

public class Example
    {
      public static string reverse_remove_parentheses(string str)
        {
            int lid = str.LastIndexOf('(');
            if (lid == -1)
            {
                return str;
            }
            else
            {
                int rid = str.IndexOf(')', lid);

                return reverse_remove_parentheses(
                      str.Substring(0, lid)
                    + new string(str.Substring(lid + 1, rid - lid - 1).Reverse().ToArray())
                    + str.Substring(rid + 1)
                );
            }
        }
  
   public static void  Main()
         {
            Console.WriteLine(reverse_remove_parentheses("p(rq)st"));
            Console.WriteLine(reverse_remove_parentheses("(p(rq)st)"));
            Console.WriteLine(reverse_remove_parentheses("ab(cd(ef)gh)ij"));
        }        
}

Sample Output:

pqrst
tsrqp
abhgefdcij

Flowchart:

Flowchart: C# Sharp Exercises - Reverse the strings contained in each pair of matching parentheses in a given string

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# program to sort the integers in ascending order without moving the number -5.
Next: C# Sharp Data Types Exercises.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming