Deadlock
Deadlock

Reputation: 330

How to split a String by using two identifiers at the same time

I have a string which i want to split into sub strings either by symbol '\n' or '\r' , for single identifier splitting we can use

string[] strsplit = str.Split('\n') ;

but in my case it is not sure weather it is '\n' or '\r' ..

can any one please tell me is there is any way to split string like the below mentioned way..

string[] strsplit = str.Split('\n' || '\r') ;

thanks in Advance and sorry for my Bad english

Upvotes: 1

Views: 1074

Answers (4)

dav_i
dav_i

Reputation: 28107

If you have the case where sometimes you have lines split with sometimes \n, sometimes \r and sometimes \r\n you can do the following

someString.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

Another option is if you want explicitly to include Environment.NewLine (\r\n) is

someString.Split(new[] { "\n", "\r", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Notice these are now strings (using " instead of ').

You can change the line skip behavior by changing the StringSplitOptions to StringSplitOptions.None

Upvotes: 4

Zbigniew
Zbigniew

Reputation: 27594

Split method has overload which accepts array of char:

string[] strsplit = str.Split(new char[] { '\n', '\r' }) ;

As mentioned in comments you can now do it this way:

string[] strsplit = str.Split('\n', '\r') ;

Upvotes: 5

Rene Niediek
Rene Niediek

Reputation: 147

You just have to pass an array of chars to the Split method

string[] arr = "Test\rTest\nTest".Split(new[] { '\r', '\n' });

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40393

You say you only want to split by either \r or \n, but in reality usually people want to also consider \r\n, since that's the default Windows line break. If you also want that, you'll need to do a little extra work. One way is to use StringReader and let it to the work for you:

var lines = new List<string>();
using (var sr = new StringReader(str)) {
    string line;
    while ((line = sr.ReadLine()) != null) {
        lines.Add(line);
    }
}
string[] strsplit = lines.ToArray();

This has slightly different behavior than dav_i's answer, when it comes to handling multiple empty lines. Just depends on what you're looking for.

Upvotes: 0

Related Questions