2014-04-27 30 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) –