Chris
Chris

Reputation: 51

split string using as separator all characters inside two parenthesis c#

I have this string

string A = "2000 to 2062 (1,2000)";

How can i get them separate like this using the parenthesis:

string B = "2000 to 2062"; 
string C = "1,2000"

Upvotes: 0

Views: 36

Answers (1)

Rufus L
Rufus L

Reputation: 37060

You can split a string on multiple characters, so simply pass in the '(' and ')' characters to the Split method:

string A = "2000 to 2062 (1,2000)";

// Split the string on the parenthesis characters
string[] parts = A.Split('(', ')');

// Get the first part (remove the trailing space with Trim)
string B = parts[0].Trim();

// It's safest to check array length to avoid an IndexOutOfRangeException
string C = parts.Length > 1 ? parts[1].Trim() : string.Empty;

// B = "2000 to 2062" 
// C = "1,2000"

Upvotes: 1

Related Questions