1

i have this string

var str="\r\nFeatures\r\nWins\r\n\r\n";

i want split on "\r\n" but between two "\r\n\r\n" have value null or whitespace

i want get result 3 items = Features Wins nullorwhitespace

i write this code but get 2 items = Features Wins

var val = str.TrimStart('\r', '\n', '\t').TrimEnd('\r', '\n', '\t').Split("\r\n");
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
jack wilsher
  • 67
  • 1
  • 10
  • `var result = str.Split(new[] { "\n" }, StringSplitOptions.None).Where(s => !s.Equals("\r")).ToArray();` – Jimi Jun 07 '20 at 20:45

3 Answers3

2

Easy option would be to just replace "\r\n\r\n" with whatever you want to see in between and then split.

var val = str
       .Replace("\r\n\r\n", "\r\nempty\r\n")
       .Split(new []{"\r\n"}, System.StringSplitOptions.RemoveEmptyEntries);
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

The problem with your current code is that the TrimEnd call gets rid of all of the trailing \r\n characters.

str.TrimStart('\r', '\n', '\t') // "Features\r\nWins\r\n\r\n"
   .TrimEnd('\r', '\n', '\t') // "Features\r\nWins"
   .Split("\r\n"); // ["Features", "Wins"]

For your example text you could do the following to get the result you want. It wont work depending on what you want to do with tabs though:

var str="\r\nFeatures\r\nWins\r\n\r\n";

var val = str.TrimStart('\r') // "\nFeatures\r\nWins\r\n\r\n"
             .TrimStart('\n') // "Features\r\nWins\r\n\r\n"
             .TrimEnd('\n') // "Features\r\nWins\r\n\r"
             .TrimEnd('\r') // "Features\r\nWins\r\n"
             .Split("\r\n"); // ["Features, "Wins", ""]
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
0

You might want to try this one as well. It also keeps the "" characters at the beginning and at the end, but they can be excluded by deleting the first and last elements of the resulting array:

var array = str.Split(new string[] { "\r\n" }, StringSplitOptions.None); // 
array = ["","Features","","Wins",""]

Here is the reference link: Split a string by another string in C#

David Buck
  • 3,752
  • 35
  • 31
  • 35