I need to often convert a "string block" (a string containing return characters, e.g. from a file or a TextBox) into List<string>
.
What is a more elegant way of doing it than the ConvertBlockToLines method below?
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestConvert9922
{
class Program
{
static void Main(string[] args)
{
string testBlock = "line one" + Environment.NewLine +
"line two" + Environment.NewLine +
"line three" + Environment.NewLine +
"line four" + Environment.NewLine +
"line five";
List<string> lines = StringHelpers.ConvertBlockToLines(testBlock);
lines.ForEach(l => Console.WriteLine(l));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List<string> ConvertBlockToLines(this string block)
{
string fixedBlock = block.Replace(Environment.NewLine, "§");
List<string> lines = fixedBlock.Split('§').ToList<string>();
lines.ForEach(s => s = s.Trim());
return lines;
}
}
}
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
You can also convert a string to a list using a separator with the split() method. The separator can be any character you specify. The string will separate based on the separator you provide. For example, you can use a comma, , , as the separator.
Description. Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
List<string> newStr = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
This will keep consecutive newlines as empty strings (see StringSplitOptions)
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());
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With