0

I would like to remove all newlines without using for loop and then the array might changed the order. The code must go at the commented line of code below.

string[] filterInput1 = tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
//(remove all Environment.NewLine or "" code goes here).
string after_resultInput1 = "";
for (int i = 0; i < filterInput1.Length; i++)
{
    string[] getDict = filterInput1[i].Split(new char[] { Convert.ToChar(tbDelim.Text) });
    after_resultInput1 += getDict[Convert.ToInt32(tbColumn.Text)] + Environment.NewLine;
}

The array of filterInput1 after Split()

filterInput1
{string[6]}
[0]: "asdasdasd|abc"
[1]: ""
[2]: ""
[3]: "1111"
[4]: ""
[5]: ""

The result must be:

filterInput1
{string[2]}
[0]: "asdasdasd|abc"
[1]: "1111"

2 Answers 2

7

Try StringSplitOptions.RemoveEmptyEntries:

string[] filterInput1 = tbInput1.Text.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.RemoveEmptyEntries
);
Sign up to request clarification or add additional context in comments.

Comments

1

Try RemoveEmptyEntries like AlexD suggested:

string[] filterInput1 = tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Good luck with your quest.

If you allow linq you could do something like this:

after_resultInput1 = string.Join(Environment.NewLine, 
    tbInput1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).
    SelectMany(s => s.Split(new char[] { Convert.ToChar(tbDelim.Text) })));

Good luck.

4 Comments

Thank you for your additional comment about LINQ. Which one will run faster?
This one runs faster than yours since yours uses += and my example uses string.Join which in turn uses StringBuilder. That is the theory, but in your case no one would ever notice.
Because of a large amount of the array, I am looking for the best solution to solve my problem above and the fastest code also. Thank you again, your code is very awesome with the additional code.
@PMay1903: The answer to "which one will run faster?" is always the same: get out a stopwatch, run the code both ways, and then you will know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.