【问题标题】:c# For every 7 letters in the string add item string to Listboxc#对于字符串中的每7个字母,将项目字符串添加到Listbox
【发布时间】:2014-09-18 18:35:56
【问题描述】:
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));
}

这是分隔文本的快速方法。

【问题讨论】:

  • 您对哪一部分有问题?这个答案可能会做你想做的事情:stackoverflow.com/a/18987605/507793
  • 通过“发布一些代码”,psoshmo 并不是要用答案覆盖您原来的问题...

标签: c# text listbox


【解决方案1】:

你可以做一个简单的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));
}

【讨论】:

  • 我建议为Substring 的第三个参数添加Math.Min(s.Length - i, 7),以防OP决定复制/粘贴并将此解决方案(盲目地)应用到非-% 7 == 0 @ 987654325@.
【解决方案2】:

将字符串分解为字符数组,并使用它来创建您的项目。这个字符串构造函数重载会有所帮助:

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() 快得多。

【讨论】:

  • -1 表示这会比 SubString 更快。 String 是一个字符数组,数组访问是 O(1)。所以这两种方法都需要大约相同的时间。
【解决方案3】:
var str = "123456776543219898989";
int count = 0;
var parts = str.GroupBy(_ => count++ / 7)
               .Select(x => string.Concat(x))
               .ToArray();

listBox1.Items.AddRange(parts);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多