How to split a string into an array of strings by newline characters in C#?
Hello everyone! I'm a beginner C# developer and I've encountered a task: I need to read a text file and split its content into separate lines. Each line should become an element of an array.
The problem is that I can't choose the correct delimiter. I tried using `String.Split('')`, but it doesn't always work. For example, if the file was created in Windows, lines are separated by the combination `\\r`, and when splitting only by ``, I end up with `\\r` characters at the end of each line.
Here's my code:
```csharp
string text = "First line\\rSecond line\\rThird line";
string[] lines = text.Split('');
foreach (var line in lines)
{
Console.WriteLine($"'{line}'");
}
```
The output looks like this:
```
'First line'
'Second line'
'Third line'
```
No answers yet.
Log in to leave an answer
Blogs
Swift Application Performance Optimization: Tips and Examples
Caching in Swift: Redis, Memcached, and Built-in Solutions for iOS/macOS
Checking for a String in a TypeScript Array: Optimization and Speed
#pragma mark in Swift 2025: Code Organization Secrets They Don't Tell You About