1

This is a pretty simple problem. If I have a string and need to .Split by something that is multiple characters what is the "correct" or easiest way to do that. I can think of how to do it w/ regex's but is there are simplier way. I've been doing it like this and I feel like this is a real hack:

text = text .Replace("\r\n\r\n", "~"); 
text = text .Replace("\n\n", "~"); 

string[] splitText = text.Split('~');

It shouldn't really matter what the original string contains but it will be something like:

sometext\r\nsomemoretext\r\n\r\nsometext2\r\n\r\nfinalbitoftext

The split should return { somtext\r\nsomemoretext, sometext2, finalbitoftext

NOTE: The big blocks of text can contain \r\n, just never two together.

1
  • Could you show an example of handsText's original value? (The string you're trying to split)? Commented May 9, 2011 at 18:27

3 Answers 3

2

This should do it:

char[] delim = {'\r','\n'};
var splitString = str.Split(delim, StringSplitOptions.RemoveEmptyEntries);

Edit:

Try using a string[] delimiter instead then, to ensure that two \r\n characters are matched. Try the code below:

string[] delims = { "\r\n\r\n" };
var splitString = str.Split(delims, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

3 Comments

will this split when it sees a singular \r\n though
Do you mean for example a big block of text \r\n some big blox of text? If so, then yes, it should.
The big block of text can contain new lines so this won't work.
1

Use a regular expression to Split it:

Regex regex = new Regex("~+");
string[] hands = regex.Split(handsText);

It's good to use the static form if you only need it every now and then. It's good to use the instance form (above) if you will be using it frequently, such as within a loop.

Similarly, you could use a regular expression to replace the \n\n and \r\n\r\n more easily.

// note: using static version; above note applies here as well
String replaced = Regex.Replace(value, "(\r\n\r\n|\n\n)+", "~");

Comments

0

I'd use:

var splitted = Regex.Split(input, "(\r\n){2,}|\n{2,}|\r{2,}", RegexOptions.ExplicitCapture);

That's splitting on any two (or more) line breaks in a row.

(Note that using (\r\n)|\n|\r){2,} doesn't work because then "\r\n" counts as two line breaks.)

Example:

  • input sometext\r\nsomemoretext\r\n\r\nsometext2\r\n\r\nfinalbitoftext
  • output is { sometext\r\nsomemoretext, sometext2, finalbitoftext }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.