1

I need to convert string to IEnumerable<string> by every newline character.

I just want the same functionality as File.ReadLines without loading any file, rather taking it from a previously loaded string.

7
  • 3
    "someString".Split('\n')? Commented Jul 2, 2021 at 15:03
  • it solved the issue @canton7 Commented Jul 2, 2021 at 15:05
  • @canton7 Actually .Split(Environment.NewLine, StringSplitOptions.None) would be a better choice. Commented Jul 2, 2021 at 15:06
  • 1
    @juharr Actually, it depends on the requirements. Who's to say their string has line endings which match Environment.NewLine? Commented Jul 2, 2021 at 15:07
  • 1
    Yes, which is what StringReader does Commented Jul 2, 2021 at 15:11

2 Answers 2

1

String.Split can split your string and give you string[]

Usage

string someString = ...;
string[] lines = someString.Split('\n');
IEnumerable<string> linesAsEnumerable = lines;

DoSomethingWithLines(linesAsEnumerable);
Sign up to request clarification or add additional context in comments.

4 Comments

Or even better IEnumerable<string> lines = someString.Split(Environment.NewLine);.
@Alejandro It has to be Split(Environment.NewLine, StringSplitOptions.None) because Environment.NewLine is a string and there is no override of Split that just takes a single string argument.
@Alejandro, yes, but I've created string[] variable to show actual return type. IEnumerable<string> slower to process than raw array
@Alejandro The question specifically specified the newline character, not the OS's new line character sequence. Given that they're not reading a file, there's no reason to assume the OS's new line string is what that string uses.
0

You could split it according to the newline character:

String[] lines = fileContenets.Split('\n');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.