0

I've a windows form with multiline text box. I'm trying to copy paste some data from excel sheet

enter image description here

I'm trying to split this values and add it to a string array using the below code

string[] languageList = language.Split('\n');

The output I'm getting is a single string

"c#javac++C"

instead of 4 strings, ie

languageList[0] = "c#"
languageList[1] = "java"
languageList[2] = "c++"
languageList[3] = "C"

Is there a way to split the excel row values using any delimiter?

3
  • 3
    "\n" is the line delimiter for Linux. Windows uses "\r\n". Better to write the code as language.Split(new[] { System.Environment.NewLine }); Commented Jun 16, 2015 at 21:13
  • 1
    I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Jun 16, 2015 at 21:25
  • @kaveman, thanks your suggestion worked, I tried out the below code language.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Commented Jun 16, 2015 at 21:30

1 Answer 1

1

Your chosen delimiter \n is the Linefeed LF character, which delimits new lines on Linux-like operating systems.

The delimiter \r\n is the Carriage Return + Linefeed CRLF character, which delimits new lines on Windows machines.

For the most robust code, use the System.Environment.NewLine property, which will pick the correct delimiter string based on the environment.

string[] languageList = language.Split(new[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

Notice the use of new[] { System.Environment.NewLine } - this is because when using a string separator with String.Split() you must pass it as a string[] argument.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I will remember this :) :) Split(new[] { System.Environment.NewLine }); was giving an error message for me, stating sting.split has some invalid arguments. so I tried Split(new string[] { Environment.NewLine }, StringSplitOptions.None); it worked

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.