Question

I am trying to split at every space " ", but it will not let me remove empty entries and then find the length, but it is treated as a syntax error.

My code:

TextBox1.Text.Split(" ", StringSplitOptions.RemoveEmptyEntries).Length

What am I doing wrong?

Was it helpful?

Solution

Well, the first parameter to the Split function needs to be an array of strings or characters. Try:

TextBox1.Text.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries).Length

You might not have noticed this before when you didn't specify the 2nd parameter. This is because the Split method has an overload which takes in a ParamArray. This means that calls to Split("string 1", "string 2", "etc") auto-magically get converted into a call to Split(New String() {"string 1", "string 2", "etc"})

OTHER TIPS

Try:

TextBox1.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length 

This is what I did:

TextBox1.Text = "1 2 3  5 6"
TextBox1.Text.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length

Result: Length = 5

// char array is used instead of normal char because ".Split()"
// accepts a char array
char[] c = new char[1];
//space character in array
c[0] = ' ';
// a new string array is created which will hold whole one line
string[] Warray = Line.Split(c, StringSplitOptions.RemoveEmptyEntries);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top