6

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);
0

3 Answers 3

8

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();
Sign up to request clarification or add additional context in comments.

Comments

0

string.Split is not suitable for what you want to do, as you can't tell it to ignore what is in the ".

I wouldn't go with Regex either, as this can get complicated and memory intensive (for long strings).

Implement your own parser - using a state machine to track whether you are within a quoted portion.

Comments

0

You can use a regular expression. Instead of splitting, specify what you want to keep.

Example:

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

MatchCollection m = Regex.Matches(tmp, @"""(.*?)""|([^ ]+)");

foreach (Match s in m) {
  Console.WriteLine(s.Groups[1].Value.Replace(" ", "") + s.Groups[2].Value);
}

Output:

abc
123
Edkk3
String;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.