Home > Back-end >  Substring between specific characters in a string multiple times
Substring between specific characters in a string multiple times

Time:08-25

Let's say we have an array of strings:

public string[] test = {"(as) (bd) (ct)", "(sdf) te"};

I want to be able to substring between the () and then add the strings to an array. No matter how many times the () occure in the string I want be able to substring the content between it.

I've tried using string.Split()

public static void Main()
        {
            //SolvePattern(3, 5, 4);
            foreach (var item in transmissions)
            {
                var test = item.Split('(', ')');
                foreach (var a in test)
                {
                    Console.WriteLine(a);
                }
            }
        }

but that would return the "te" aswell, which is not between ().

Also worth noting is that the solution should not be using regex.

CodePudding user response:

If it is like that then you could do something like this:

string[] test = { "(as) (bd) (ct)", "(sdf) te" };
var result = test.SelectMany(t => t.Split())
              .Where(t => t.StartsWith("(") && t.EndsWith(")"))
              .Select(t => t.Trim(new char[] {'(',')'}));
foreach(var item in result) {
   Console.WriteLine(item);
}
  • Related