0

I have this code:

while(!sr1.EndOfStream)
{
    radek1 = sr1.ReadLine();
    Console.Write(radek1);
    Console.WriteLine();
    string[] split1 = radek1.Split(new char[] { ' ', '???' });
}

I read a string array from a file.txt and I need to split with spaces and with enters, so I want to exchange these? For something that represents Enter

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Štěpán Šubík
  • 109
  • 2
  • 3
  • 10
  • 1
    possible duplicate of [How to insert newline in string literal?](http://stackoverflow.com/questions/4085739/how-to-insert-newline-in-string-literal) – Fedor Oct 05 '14 at 16:59

3 Answers3

7

By enter, you probably mean New Line. In most cases, this would be what you're looking for:

string newLine = Environment.NewLine; //Updated to Sergey Volegov's suggested

In most cases, Environment.NewLine is equal to "\r\n", but sometimes it's only \n so it's wiser to use Environment.NewLine.

\r is the carriage return.
\n is a new line.

Think of it as a typewriter. You need to go back to the beginning of the row (\r) and then down a line (\n)

Due to the fact that Environment.NewLine is a string, you're going to want to Split on Strings, and not Chars:

string[] split1 = radek1.Split(new string[] { " ", Environment.NewLine });
Guy Passy
  • 694
  • 1
  • 9
  • 32
2

Use this :

Environment.NewLine.ToCharArray();

As @Guffa also said you can also have :

string[] split1 = radek1.Split(new string[] { " ", Environment.NewLine }, StringSplitOptions.None));  

The second one splits based on spaces and new lines.
The first one though, splits by \r, and \n individually. so For the correct behavior you want to use the second method.

Hossein
  • 24,202
  • 35
  • 119
  • 224
2

That depends on where the file comes from and how it was created.

If it was created on the same system, it will most likely use the native newline combination for that specific system, and you can use the Environment.NewLine constant:

string[] split1 = radek1.Split(new string[] { " ", Environment.NewLine }, StringSplitOptions.None);

Note that Environment.NewLine is a string and can contain more than one character, so you need to split on strings, and the call needs a StringSplitOptions parameter as there is no overload without it.

If the file comes from a different system (or was created with newlines typical for a different system), you would need to specify that specific string. For example the two character string used in a Windows system:

string[] split1 = radek1.Split(new string[] { " ", "\r\n" }, StringSplitOptions.None);

You can also include the most common newline combinations, if you need to handle files coming from different systems:

string[] split1 = radek1.Split(new string[] { " ", "\r\n", "\n" }, StringSplitOptions.None);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005