1

I am trying to split a string into two arrays.

The first array has data at the beginning of the string which is split by the \t (tab) character, and the remainder somes after the first newline character (\n).

I tried this, thinking that's what I wanted:

string[] pqRecords = pqRequests.ToString().Split('\n');

I also tried this:

internal static readonly string segment = Environment.NewLine + "\t";
string[] pqRecords = pqRequests.ToString().Split(segment);

unfortunately the Split method will only take a single character.

I know there are vbcr in my pqRequests string variable because when I mouse over it and look at the text visualize there is the first line with tabs, everything else is on it's own line.

This data is taken from a txt file, and in the file, when opened in Notepad++, I can see the CR characters.

Is there an alternative constant in c# I should use for these CR characters?

Our Man in Bananas
  • 5,809
  • 21
  • 91
  • 148
  • I think you may want to try `Environment.NewLine` but it's a string, so you have to use another overload of `Split` – King King Nov 21 '13 at 14:35
  • `File.ReadAllLines(filename)`. –  Nov 21 '13 at 14:38
  • 1
    Use this http://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net – Oleh Nov 21 '13 at 14:38
  • I tried `string[] pqRecords = pqReq.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);` but only got a single string in my array instead of several lines. – Our Man in Bananas Nov 21 '13 at 15:13

2 Answers2

5

string.Split will happily accept multiple separator characters. You just have to pass them in as an array:

internal static readonly string segment = Environment.NewLine + "\t";
string[] pqRecords = pqRequests.ToString().Split(segment.ToArray());

Of course you can (and should) write the same more clearly as

internal static readonly char[] separators = new[] { '\n', '\t' };
string[] pqRecords = pqRequests.ToString().Split(separators);
Jon
  • 428,835
  • 81
  • 738
  • 806
2

The carriage return character is represented by '\r', is that what you need?

BobHy
  • 1,575
  • 10
  • 23