1

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.

6
  • 1
    This should be a lot simpler with regex Commented Aug 24, 2022 at 21:00
  • 1
    What's the reason for not allowing regex? Commented Aug 24, 2022 at 21:00
  • 1
    It could be a homework question which has arbitrary constraints. Commented Aug 24, 2022 at 21:05
  • As @Ibrennan208 said, it's a problem for school! Commented Aug 24, 2022 at 21:47
  • Will your data always match the example provided? Or is it possible that you will have to parse a string such as "test(inside)()12((()"? Will the parentheses always be a single pair of open and close? or is it possible to have multiple in a row as in my example string? Commented Aug 25, 2022 at 0:09

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

An issue with this is that you are relying on a split on whitespace. Although the example shows whitespace, they don't clarify if that is consistent with all of their data sets. The only thing they do specify is that the string should be within parentheses.
@Ibrennan208, in first sentence I clearly specified "if it is like that". In a real world this would be a job of regex anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.