使用两个括号内的所有字符作为分隔符分割字符串c#

时间:2020-04-22 02:11:18

标签: c# parsing split

我有这个字符串

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

我如何使用括号将它们分开:

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

1 个答案:

答案 0 :(得分:1)

您可以将字符串拆分为多个字符,因此只需将'('')'字符传递给Split方法:

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"