przemyslawklys
przemyslawklys
CC#
Created by przemyslawklys on 3/11/2023 in #help
❔ Split on new line preserving empty line
So I'm trying to create a method that given a string with Environment.NewLine or \r\n or \r or \n converts it to an array while preserving the new lines in form of an empty line.
string[] newLineArray = { Environment.NewLine };
string[] textArray1 = text.Split(newLineArray, StringSplitOptions.None);
string[] textArray = text.Split(Environment.NewLine.ToArray(), StringSplitOptions.None);
string[] newLineArray = { Environment.NewLine };
string[] textArray1 = text.Split(newLineArray, StringSplitOptions.None);
string[] textArray = text.Split(Environment.NewLine.ToArray(), StringSplitOptions.None);
While testing things I am having hard time understanding why there is difference between first 2 lines vs what is in 3rd line. The first 2 lines when given a string such as "First line\r\nAnd more in new line" split into array of 2 strings, while the output of textArray splits into 3, with an empty line. In the end I want to add to my C# library that can create Word Documents ability for people to be able to provide string with new lines of different kind and that would be treated in proper manner. But for some reason Split on newLineArray delivers no empty lines, and the only time I can get it to deliver empty lines is when using Environmnet.NewLine.ToArray()
private WordParagraph ConvertToTextWithBreaks(string text) {
string[] newLineArray = { Environment.NewLine, "\n", "\r\n", "\n\r" };
//string[] newLineArray = { Environment.NewLine };
string[] textArray = text.Split(newLineArray, StringSplitOptions.None);
//string[] textArray = text.Split(Environment.NewLine.ToArray(), StringSplitOptions.None);

WordParagraph wordParagraph = null;
foreach (string line in textArray) {
if (line == "") {
wordParagraph = AddBreak();
} else {
wordParagraph = new WordParagraph(this._document, this._paragraph, new Run());
wordParagraph.Text = line;
this._paragraph.Append(wordParagraph._run);
}
}
return wordParagraph;
}
private WordParagraph ConvertToTextWithBreaks(string text) {
string[] newLineArray = { Environment.NewLine, "\n", "\r\n", "\n\r" };
//string[] newLineArray = { Environment.NewLine };
string[] textArray = text.Split(newLineArray, StringSplitOptions.None);
//string[] textArray = text.Split(Environment.NewLine.ToArray(), StringSplitOptions.None);

WordParagraph wordParagraph = null;
foreach (string line in textArray) {
if (line == "") {
wordParagraph = AddBreak();
} else {
wordParagraph = new WordParagraph(this._document, this._paragraph, new Run());
wordParagraph.Text = line;
this._paragraph.Append(wordParagraph._run);
}
}
return wordParagraph;
}
What I am missing?
87 replies