简体   繁体   中英

What is the best way to split “[{a},{b},{c}]” into a string array “a,b,c”

What is the best way to split "[{a},{b},{c}]" into a string array t such as:

t[0] == "a"
t[1] == "b"
t[2] == "c"

Consider the input string as verbatim, square and curly brackets are actually there.

UPDATE: Here is a more concrete sample of what I need to split

[{ pk:"4",id:"4",cb_program_id:"2.0000",DataSource:"1",Status:"0",CutoffDate:"15/10/2012 14:05:04" }, 
{ pk:"3",id:"3",cb_program_id:"2.0000",DataSource:"1",Status:"0",CutoffDate:"15/10/2012 14:05:02" }, ... ]

Use String.Split to get rid of all the unwanted characters.

"[{a},{b},{c}]".Split(new char[] {'[', ']', '{', '}', ','}, StringSplitOptions.RemoveEmptyEntries);

Edit: Following OP's edit, @Daniel's answer is more suitable for maintaining integrity of the substrings.

var t = s.Trim('[', ']').Split(',').Select(x => x.Trim('{', '}')).ToArray();

This will first remove the outer brackets, split by the comma and remove the curly braces at the beginning and the end of the result.

To cover embedded special characters like comma or curly braces, you need to escape them, because otherwise there will exist ambiguous strings that could be splitted in multiple ways.

This is the working example:

string str = "[{a},{b},{c}]";
string[] t = str.Split(new char[] { '[', ']', '{', '}', ',' },
             StringSplitOptions.RemoveEmptyEntries)
             .ToArray();

Output:

t[0] == "a"
t[1] == "b"
t[2] == "c"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM