Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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: Write a C# program to check if a given number present in an array of numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.