根据字符串长度 .NET 使用换行符拆分多行文本框文本



我有一个多行文本框,我想制作一个字符串数组,但是当字符串超过 60 个字符时,我想连接一个新行。

所以假设我有一条短信:

A geologic period is one of several subdivisions of geologic time enabling cross-referencing of rocks and geologic events from place to place. These periods form elements of a hierarchy of divisions into which geologists have split the earth's history.

转换为:

A geologic period is one of several subdivisions of geologic n
time enabling cross-referencing of rocks and geologic events n
from place to place. These periods form elements of a        n
hierarchy of divisions into which geologists have split the  n
earth's history.

所以要这样做,我计划使用

array_strings = myMultilineText.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)

然后遍历数组中的每个字符串,例如

 For index = 0 To array_strings.GetUpperBound(0)
    If array_strings(index).Length < 60 Then
        MessageBox.Show(array_strings(index))
    Else
       'add new line...
    End If
 Next

有没有更好的方法可以做到这一点?

如果您希望文本换行TextBox只需将"WordWrap"属性设置为 True。但是如果你想要一个算法,你可以在 c# 中使用此代码(如果你愿意,你可以把它转换为 VB,它是如此简单)

c# 代码:

        string longString = "Your long string goes here...";
        int chunkSize = 60;
        int chunks = longString.Length / chunkSize;
        int remaining = longString.Length % chunkSize;
        StringBuilder longStringBuilder = new StringBuilder();
        int index;
        for (index = 0; index < chunks * chunkSize; index += chunkSize)
        {
            longStringBuilder.Append(longString.Substring(index, chunkSize));
            longStringBuilder.Append(Environment.NewLine);
        }
        if (remaining != 0)
        {
            longStringBuilder.Append(longString.Substring(index, remaining));
        }
        string result = longStringBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray());

VB代码(通过开发者融合转换工具转换

):
Dim longString As String = "Your long string goes here..."
Dim chunkSize As Integer = 60
Dim chunks As Integer = longString.Length  chunkSize
Dim remaining As Integer = longString.Length Mod chunkSize
Dim longStringBuilder As New StringBuilder()
Dim index As Integer
index = 0
While index < chunks * chunkSize
    longStringBuilder.Append(longString.Substring(index, chunkSize))
    longStringBuilder.Append(Environment.NewLine)
    index += chunkSize
End While
If remaining <> 0 Then
    longStringBuilder.Append(longString.Substring(index, remaining))
End If
Dim result As String = longStringBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray())

最新更新