Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string to array, remove empty spaces

I have a question about splitting string. I want to split string, but when in string see chars "" then don't split and remove empty spaces.

My String:

String tmp = "abc 123 \"Edk k3\" String;";

Result:

1: abc
2: 123
3: Edkk3  // don't split after "" and remove empty spaces
4: String

My code for result, but I don't know how to remove empty spaces in ""

var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
                {
                    if (i % 2 == 1) return new[] { s };
                    return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
                }).ToList();

Or but this doesn't see "", so it splits everything

string[] tmpList = tmp.Split(new Char[] { ' ', ';', '\"', ',' }, StringSplitOptions.RemoveEmptyEntries);
like image 555
Le Viet Hung Avatar asked Nov 30 '12 13:11

Le Viet Hung


1 Answers

Add .Replace(" ","")

String tmp = @"abc 123 ""Edk k3"" String;";
var tmpList = tmp.Split(new[] { '"' }).SelectMany((s, i) =>
{
    if (i % 2 == 1) return new[] { s.Replace(" ", "") };
    return s.Split(new[] { ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
}).ToList();
like image 156
SergeyS Avatar answered Oct 06 '22 01:10

SergeyS