我有一个多行文本框,我想创建一个字符串数组,但是当字符串超过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
有更好的方法吗?
答案 0 :(得分:4)
如果您希望将文本包装在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())