我需要读取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);
};
}
答案 0 :(得分:2)
方法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
答案 1 :(得分:1)
如果要在特定尺寸之前拆分单词,请使用此扩展程序:
/// <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 to Split Text into Specific Sizes « OmegaMan's Musings
答案 2 :(得分:0)
此Substring overload接受开始索引和长度。您正在传递body.Text.Length的长度为第二个(长度)参数,这可能是整个字符串的长度。您应该通过body.Text.Length - startIndex
。