Converts the contents of a delimited string into an Array, removing empty, or whitespace entries.
/// <summary>
/// Convert the <paramref name="delimitedString"/> into an array of substrings,
/// separated by the specified <paramref name="separator"/> character.
/// </summary>
/// <param name="delimitedString">The delimited string content.</param>
/// <param name="separator">The separator to split on.</param>
/// <param name="trimAndRemoveNullEntries">Whether or not to trim each substring and remove null entries.</param>
/// <returns>An array of substrings comprised of <paramref name="delimitedString"/>, separated by the specified <paramref name="separator"/> character.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="delimitedString"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="separator"/> is less than or equal to zero.</exception>
/// <remarks>Empty values will not be included in the resulting array.</remarks>
public static string[] DelimitedStringToArray(
string delimitedString,
char separator = ',',
bool trimAndRemoveNullEntries = true
)
{
// Ensure.IsNotNull(delimitedString, "delimitedString");
// Ensure.IsGreaterThan(separator, 0, "separator");
var splitStrings = delimitedString.Split(separator, StringSplitOptions.RemoveEmptyEntries);
if (!trimAndRemoveNullEntries)
{
return splitStrings;
}
var trimmedEntries = new List<string>(splitStrings.Length);
for (var i = 0; i < splitStrings.Length; i++)
{
var entry = splitStrings[i].Trim();
if (!string.IsNullOrEmpty(entry))
{
trimmedEntries[i] = entry;
}
}
return trimmedEntries.ToArray();
}
//
// Xunit Tests
[Theory]
[InlineData("", 0)]
[InlineData(",, ,", 0)]
[InlineData(",two", 1)]
[InlineData("one", 1)]
[InlineData("one,", 1)]
[InlineData("one, ", 1)]
[InlineData("one two three", 1)]
[InlineData("one, two, three", 3)]
public void ShouldSplitStringByDelimiter(string content, int expectedLength)
{
Assert.True(Common.ToDelimitedArray(content).Length == expectedLength);
}