Search code examples
c#stringdotnetnuke

Joining strings by ClientAPI.COLUMN_DELIMITER and then splitting by the same delimiter adds two new elements


I have the following

string.Join(ClientAPI.COLUMN_DELIMITER),(new string[] {"1", "2" })).Split(ClientAPI.COLUMN_DELIMITER.ToCharArray())

I expect the result to be an array of length 2, instead two new empty strings are added.

Why does this happen and how can I avoid it in the Join method. (I have no control on Split).

string join and split

EDIT

enter image description here


Solution

  • Why does this happen [..] ?

    Documentation for the String.Split Method (Char[]) tell us :

    Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding element in the returned array contains Empty

    That's why you've got empty string in your result array (not because of the Join method as you wrote in a comment).

    EDIT: With this example, Split method gives back your "input" array :

    string.Join("~|~", new string[] { string.Empty, "2" }).Split(new string[] { "~|~" }, StringSplitOptions.None)
    

    EDIT-2: Try this :

    string.Join(ClientAPI.COLUMN_DELIMITER, new string[] { string.Empty, "2" }).Split(ClientAPI.COLUMN_DELIMITER, StringSplitOptions.None);