分隔字符串并将其放在列表框中

时间:2014-11-10 17:46:09

标签: c# regex string listbox

我有一个字符串:

one,one,one,one,two,two,two,two,three,three,three,three,four,four,four,four,...

我想在每四个逗号后划分它并将其存储到一个列表框中,如下所示:

one,one,one,one,
two,two,two,two,
three,three,three,three,
four,four,four,four,
...

应该采取什么措施?我是否应该使用正则表达式以某种方式划分这个字符串?

由于

2 个答案:

答案 0 :(得分:2)

此LINQ通过在逗号上分隔将您的输入分成单个字符串,然后使用index in the Select method一次将四个项目组合在一起,最后再将这四个项目连接成一个字符串。

var input = "one,one,one,one,two,two,two,two,three,three,three,three";  // and so on

var result = input.Split(',')
                  .Select((s, i) => new {s, i})
                  .GroupBy(pair => pair.i / 4)
                  .Select(grp => string.Join(",", grp.Select(pair => pair.s)) + ",");

结果是一个字符串集合,其中第一个(根据您的输入)是"一个,一个,一个,",然后第二个是"两个,两个二,二,"等等...

enter image description here

从那里开始,只需将其设置为DataSourceItemsSource或类似内容,具体取决于您使用的技术。

答案 1 :(得分:2)

Linqless替代品;

int s = 0, n = 0, len = inputString.Length;

for (var i = 0; i < len; i++) {
    if (inputString[i] == ',' && ++n % 4 == 0 || i == len - 1)  {
        aListBox.Items.Add(inputString.Substring(s, i - s + 1));
        s = i + 1;
    }
}