2014-09-18 32 views
-2
ListBox box = GetListBox(); //placeholder for the sample 
string s = "123456776543219898989"; 
char[] c = s.ToCharArray(); 
for(int i=0;i<c.Length;i+=7) 
{ 
    box.Items.Add(new string(c, i, 7)); 
} 

這是分隔文本的快速方法。c#對於字符串中的每7個字母,將項目字符串添加到列表框

+0

你吃的什麼部分有問題?這個答案有可能做你想做的事情:http://stackoverflow.com/a/18987605/507793 – Matthew 2014-09-18 18:38:23

+0

通過「發佈一些代碼,」psoshmo並不意味着用你的答案覆蓋你原來的問題... – Michael 2014-09-19 16:44:05

回答

0

你可以做一個簡單的for循環

ListBox box = null;//set it yourself 
for(int i = 0; i < s.Length; i+= 7) 
{ 
    box.Items.Add(s.SubString(i, Math.Min(s.Length - i, 7)); 
} 
+0

如果OP決定複製/粘貼並將此解決方案(盲目地)應用於其他位置,則建議在'Substring'的第三個參數中引入'Math.Min(s.Length - i,7)', '%7 == 0''字符串。 – Michael 2014-09-18 19:01:32

+0

@Michael好點,編輯和感謝 – Steve 2014-09-18 19:05:28

0

將字符串分解爲字符數組,然後使用它來創建項目。此字符串構造函數重載將幫助:

http://msdn.microsoft.com/en-us/library/ms131424.aspx

此代碼只是一個樣本。你真正需要取決於您希望如何處理這種情況如在原有字符串中的字符數不整除7

ListBox box = GetListBox(); //placeholder for the sample 
string s = "123456776543219898989"; 
char[] c = s.ToCharArray(); 
for(int i=0;i<c.Length;i+=7) 
{ 
    box.Items.Add(new string(c, i, 7)); 
} 

我也能做到這一點直接上線,而不是創建該陣列,但這應該比重複調用.SubString()快得多。

+0

- 1表示這將比SubString更快。字符串是一個字符數組,數組訪問是O(1)。所以這兩種方法都需要大約相同的時間。 – Steve 2014-09-18 18:45:58

0
var str = "123456776543219898989"; 
int count = 0; 
var parts = str.GroupBy(_ => count++/7) 
       .Select(x => string.Concat(x)) 
       .ToArray(); 

listBox1.Items.AddRange(parts); 
相關問題