I need to often convert a \"string block\" (a string containing return characters, e.g. from a file or a TextBox) into List
ou can use RegEx.Split to split directly using the Enviroment.NewLine.
public static List<string> ConvertBlockToLines(this string block)
{
return Regex.Split(block, Environment.NewLine).ToList();
}
Have you tried splitting on newline/carriage return and using the IEnumerable ToList extension?
testBlock.Split( new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries )
.ToList()
If you want to keep empty lines but may have both linefeed and carriage return.
textBlock.Replace( "\r\n", "\n" ).Replace( "\r", "\n" ).Split( '\n' ).ToList();
Hmm. You know that string
now has a .Split() that takes a string[]
array, right?
So ...
string[] lines = data.Split(
new string[1]{ Environment.NewLine },
StringSplitOptions.None
);
LINQ!
var linesEnum = testBlock.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
List<string> lines = linesEnum.ToList();
No need to convert to your special sign:
List<string> strings = str.Split(new string[] {Environment.NewLine}, StringSplitOptions.None).ToList();
strings.ForEach(s => s = s.Trim());
List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
This will keep consecutive newlines as empty strings (see StringSplitOptions)