How can I split a Quoted String?

Hi all,

I have a string similar to this:
"1.1.1" "2.2.2 Possibly Some Info Here" "3.3.3 And Maybe Some Info Here Too!"

I would like the array to be
1.1.1
2.2.2 Possibly Some Info Here
3.3.3 And Maybe Some Info Here Too!

Looks like C# (2005) has no native way to do this (unless I am lissing something.

Any ideas how this can be achieved?

Thanks,

James
LVL 4
James AtkinSenior Principle Software EngineerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Richard LeeConnect With a Mentor Software EnthusiastCommented:
Try the following code. This code assumes that your string may be prefixed and suffixed with quotation marks.

DaTribe



string testString = "\"1.1.1\" \"2.2.2 Possibly Some Info Here\" \"3.3.3 And Maybe Some Info Here Too!\"";
			string[] result = testString.Trim(new [] {'\"'}).Split(new [] {"\" \""}, StringSplitOptions.None);

Open in new window

0
 
kaylanreilorConnect With a Mentor Commented:
Just use the Split() method of the string class...
Char[] _separators = new Char[] { '"' };
string[] myStrings = theString.Split(_separators, StringSplitOptions.RemoveEmptyEntries);

Open in new window

0
 
James AtkinSenior Principle Software EngineerAuthor Commented:
Hi,
These both almost work..
DaTribe, if there is more than one space between the delimited items, the delimeter does not match :-(
kaylanreilor, you get blank lines in the returned array (the space(s) delimiting the string.

I can mod the result to remove the blank lines, but is there a more direct way; maybe a regex split?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
kaylanreilorCommented:
It is because you have whitespaces between '"' in your original string. You cannot remove them since it will remove the necessary whitespaces. So I suppose that you remove afterward in the array.
0
 
Roshan DavisConnect With a Mentor Commented:

Regex re = new Regex("\\s*\"");
string testString = "\"1.1.1\" \"2.2.2 Possibly Some Info Here\" \"3.3.3 And Maybe Some Info Here Too!\"";
string [] strAry = re.Split(testString);

Open in new window

0
 
Shahan AyyubConnect With a Mentor Senior Software Engineer - iOSCommented:
Try this one:  

            string str = "1.1.1\" \"2.2.2 Possibly Some Info Here\" \"3.3.3 And Maybe Some Info Here Too!";
            Regex re=new Regex("\"\\s*\"");
            string[] s=re.Replace(str,"\0").Split('\0');
0
 
James AtkinSenior Principle Software EngineerAuthor Commented:
Thanks everyone for all the suggestions.
As there are several great solutions, I feel it would be right to split the points in this case - hope this is ok with everyone.
James
0
All Courses

From novice to tech pro — start learning today.