Click here to Skip to main content
15,905,683 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
For such a string value:
C#
string s = "[\"A01B001\",\"BM OB-A-1\",\"A01\",\"BENCHMARK\",\"PRIVATE\",\"BRASS DISK\"]";

How can it be converted to a string[]? Thanks for your help.

What I have tried:

How can a string to converted to a string[]?
Posted
Updated 17-Aug-16 6:28am
Comments
Mehdi Gholam 17-Aug-16 12:11pm    
Looks like a json encoded string.

try this
one of the method,
C#
string s = "[\"A01B001\",\"BM OB-A-1\",\"A01\",\"BENCHMARK\",\"PRIVATE\",\"BRASS DISK\"]";
       string[] result = s.Trim(new char[] { '[', ']' }).Split(',').Select(k => k.Trim('"')).ToArray();
 
Share this answer
 
Comments
s yu 17-Aug-16 12:23pm    
Wonderful! Works perfectly. Thanks.
Karthik_Mahalingam 18-Aug-16 2:29am    
welcome :)
I'm just guessing you want to split it into the items which are separated by commas, and that bits simple:
C#
string[] parts = s.Split(',');

But if you also want to dump the square brackets and the double quotes, that's a little more work:
C#
string s = "[\"A01B001\",\"BM OB-A-1\",\"A01\",\"BENCHMARK\",\"PRIVATE\",\"BRASS DISK\"]";
string[] parts = s.Split("\"[],".ToArray(), StringSplitOptions.RemoveEmptyEntries);
Will do it.
 
Share this answer
 
In addition to Solutions 1 and 3.
When you want to do pattern matching, the tool to use is Regular Expressions.
Basically, RegEx is used when you want to check that a string match or contain a given format like date, floating point number, integer, phone number ...
One usage is also to split a string in pieces.

Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900