簡體   English   中英

使用新行拆分多行文本框文本,具體取決於字符串長度.NET

[英]split multiline textbox text with new line depending on string length .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代碼(通過developerfusion轉換工具轉換 ):

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM