Juan Carlos Cruz
Juan Carlos Cruz

Reputation: 27

How to split a text file by a given separator in c#

I'm having a trouble with a program. I got to read a file *.txt and split it by a given character, for example: the file contains this :

rotbrow
yabector
gamerue

So when I insert the given separator that is a, it should separate the lines like this:

rotbrow
ya
bector
ga
merue

but it prints them like this without the a :

rotbrow
ya
bector
ga
merue

This is the code I am using :

foreach (string line in  File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ArchivoaSeparar.txt"))
{
    string[] parts = line.Split(cadenaTextBox.Text.ToCharArray());

    foreach (string item in parts)
    {
        listBox1.Items.Add(item);
    }
}

I don't understad why dont show the given separator (the a in the las example) and I have to to do this with any text entered and a given separator.

Hope that you can help me with this.

Upvotes: 1

Views: 1623

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You will not get the delimater as part of return value after the split operation. you can have extra logic to add that as below:

foreach (string line in File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ArchivoaSeparar.txt"))
            {
                String checkItem = cadenaTextBox.Text.ToString();
                string[] parts = line.Split(checkItem.ToCharArray());

                foreach (string item in parts)
                {
                    listBox1.Items.Add((line.Contains(checkItem) ? item + checkItem : item));
                }
            }

Upvotes: 1

Hans Kesting
Hans Kesting

Reputation: 39284

When you split a string on some separater, that separator is not part of the resulting parts. If you want to see that "a", you need to add it back in manually (on every part execpt the last).

By the way: that ToCharArray will not have the effect you probably want: if you enter "or" as separator, then both "r" and "o" are independent separator, so they split whether or not they are together (the string would split on a single "o" and split double on "ro" or "or".)

Upvotes: 2

Related Questions