c# - 文本框按字符数分割文本

标签 c#

我需要读取 70 个字符 block 并将其发送到终端模拟器。我真的不知道当子字符串时如何做到这一点 长度,不能是字符串中更大的数据量(微软生成错误)。文本框中的最后一行始终小于 70。

有谁知道更好的方法吗?

打开自动换行后,文本框可以接受 1000 个字符。

int startIndex = 0;
int slength = 70;

for (int i = 0; i < body.Text.Length; i += 70)
{
    if(body.Text.Length < 70)
    {
        String substring1 = body.Text.Substring(startIndex, body.Text.Length);
        CoreHelper.Instance.SendHostCommand("¤:5H¤NCCRMKS / " + body.Text, UIHelper.Instance.CurrentTEControl, true, true);
    };

    if (body.Text.Length > 70)
    {
        String substring1 = body.Text.Substring(startIndex, slength);
        CoreHelper.Instance.SendHostCommand("¤:5H¤NCCRMKS / " + body.Text, UIHelper.Instance.CurrentTEControl, true, true);

    };
}

最佳答案

方法 1(传统子字符串)- 最快:

string str = "123456789";

int currentIndex = 0;
int pageSize = 7;
List<string> results = new List<string>();
while(true)
{
    int length = Math.Min(pageSize, str.Length - currentIndex);
    string subStr = str.Substring(currentIndex, length);
    results.Add(subStr);

    if (currentIndex + pageSize >= str.Length - 1)
        break;

    currentIndex += pageSize;
}

方法 2 (Linq):

Linq 的 Skip 和 Take 的组合也能达到这个目的。这称为分页:

String str = "123456789";

int page = 0;
int pageSize = 7; // change this to 70 in your case
while(true)
{
    string subStr = new string(str.Skip(page * pageSize).Take(pageSize).ToArray());
    Console.WriteLine(subStr);


    page++;

    if (page * pageSize >= str.Length)
        break;
}

打印:

1234567
89

关于c# - 文本框按字符数分割文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311505/

相关文章:

c# - 跨机器复制网页的简单方法?

c# - Poco-Viewmodel 的 Control.Databindings 意外行为

c# - 将 WCF 服务引用添加到 Java 应用程序

c# - C# (.NET) 的 strtotime

c# - 如何获取嵌入式资源的路径?

c# - 使用javascript将值从一个列表框移动到另一个列表框,然后使用c#读取值

C# 在任务栏上显示文本 | window 10

c# - 我的上下文不是从 Entity Framework Core 中的 DbContext 继承的

c# - CakeBuild:DotNetCoreBuild 与 DotNetBuild?

c# - Windows 服务 - 迁移到 64 位。 '64-bit benefits'的实现步骤