我有一个多行文本框,我想制作一个字符串数组,但是当字符串超过 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 Conversion Tool 转换):
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())
