2014-04-27 41 views
1

我有一个动态的字符串,如:计数动态项目,然后拆分

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

的空间是因为该字符串是从的nchar(80)从SQLSERVER type.I要算,这将分裂,然后将物品拆分它们。

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

的问题是,该字符串被分裂并且计数是72 items.4项10 11 1 2和68空项 正确的结果必须是4。我需要的项目此计数用于将来使用a ...

有什么建议吗?

+0

不应该正确的计数是3吗? –

+0

这是不必要的复杂 - 只需调用Split而不传递项目数量,它就知道该怎么做。 –

+0

@ChrisLaplante我认为他需要在后面的循环中使用计数(据我了解)。 –

回答

1

好吧,除非我失去了一些东西,那就是:

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 
+0

字符串是“10 11 1 2 ... 70spaces ....”,因为它来自nchar(80)sqlserver类型。随着你的代码再次给我72 – Apollon

+0

@Apollon哦,我现在明白了,当然,检查我的编辑。 –

+0

谢谢Dimitar.You已经做到了 – Apollon

2

从原来的字符串修剪的空间,然后分裂

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

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

这将为您提供expeected输出

HSlist.Length是4

HSlist[0]是10

HSlist[1]是11

HSlist[2]是1

HSlist[3]是2

我希望这是你真正想实现。

+0

yes.Exactly我想要的。我使用trimEnd()。我认为是相同的。谢谢 – Apollon

+0

yest,其相同(y) –