Question

I have a dynamic string Eg:

string HtS ="10 11 1 2       '...many spaces...'       ";

The spaces are because the string is from nchar(80) from sqlserver type.I want to count the items that will splitted and then split them.

int cP = Regex.Matches(HtS, " ").Count;
string[] HSlist = HtS.Split(new char[] { ' ' }, cP);

the problem is that the string is splitted and the count is 72 items.4 items 10 11 1 2 and 68 empty items The right result must be 4. I need this count of items for future use in a for...

any suggestion?

Was it helpful?

Solution 2

Well, unless I'm missing something, here it is:

string HtS = "10 11 1 2       ".Trim(); // removes the spaces at the end
int count = HtS.Count(x => x.Equals(' ')); // = 3 -> counting the spaces
string[] HSlist = HtS.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int elementsCount = HSlist.Length; // = 4

OTHER TIPS

Trim the spaces from the original string and then split

 string HtS = "10 11 1 2                         ..lots of spaces.......";
 HtS = HtS.Trim();

 string[] HSlist = HtS.Split(' ');

This will provide you with expeected output

HSlist.Length is 4

HSlist[0] is 10

HSlist[1] is 11

HSlist[2] is 1

HSlist[3] is 2

I hope this is what you actually wanted to achieve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top