[英]textbox split text by number of characters
我需要讀取70個字符塊並發送到終端模擬器。 我真的不確定如何在子串長度時這樣做,不能在字符串中產生更大量的數據(microsoft生成錯誤)。 文本框中的最后一行始終小於70。
有誰知道更好的方法嗎?
TextBox可以在打開自動換行功能時接受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
如果要在特定大小之前拆分單詞,請使用此擴展名:
/// <summary>Use this function like string.Split but instead of a character to split on,
/// use a maximum line width size. This is similar to a Word Wrap where no words will be split.</summary>
/// Note if the a word is longer than the maxcharactes it will be trimmed from the start.
/// <param name="initial">The string to parse.</param>
/// <param name="MaxCharacters">The maximum size.</param>
/// <remarks>This function will remove some white space at the end of a line, but allow for a blank line.</remarks>
///
/// <returns>An array of strings.</returns>
public static List<string> SplitOn( this string initial, int MaxCharacters )
{
List<string> lines = new List<string>();
if ( string.IsNullOrEmpty( initial ) == false )
{
string targetGroup = "Line";
string pattern = string.Format( @"(?<{0}>.{{1,{1}}})(?:\W|$)", targetGroup, MaxCharacters );
lines = Regex.Matches(initial, pattern, RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled)
.OfType<Match>()
.Select(mt => mt.Groups[targetGroup].Value)
.ToList();
}
return lines;
}
用法
var text = @"
The rain in spain
falls mainly on the
plain of Jabberwocky
falls.";
foreach ( string line in text.SplitOn( 11 ) )
Console.WriteLine( line );
/* Result
The rain in
spain falls
mainly on
the plain
of
Jabberwocky
falls.
*/
這是我的博客文章C#:String Extension SplitOn將文本拆分為特定尺寸«OmegaMan's Musings
此Substring重載接受起始索引和長度。 您正在傳遞body.Text.Length的長度為第二個(長度)參數,這可能是整個字符串的長度。 你應該傳遞body.Text.Length - startIndex
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.