繁体   English   中英

如何包含两个文本框文本?

[英]How to include two text boxes texts?

我想在一个文本框中包含两个文本框文本,因为它们都是多行。 但是我想要特殊形式的包含,换句话说,我想像这样包含它们

textbox 1 texts: '' help''' '' other''  
textbox 2 texts:' 1'     '2'   '' 3''  
results: help1 _  help2  _ help3  
other1_other2_other3

多行文本框返回一个字符串数组,其中包含Lines属性中的Lines 你可以做这样的事情

string[] words = textBox1.Lines;
string[] numbers = textBox2.Lines;
var resultLines = new string[words.Length];
var sb = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
    sb.Length = 0; // Reset StringBuilder for the next line.
    for (int j = 0; j < numbers.Length; j++) {
        sb.Append(words[i]).Append("-").Append(numbers[j]).Append("_");
    }
    if (sb.Length > 0) {
        sb.Length--; // remove the last "_"
    }
    resultLines[i] = sb.ToString();
}
resultsTextBox.Lines = resultLines;

首先我们得到wordsnumbers数组。 然后,我们为结果创建一个新数组。 由于我们希望每个单词都有一条结果行,因此我们将其设置为words.Length的长度。

然后,我们遍历单词。 我们使用StringBuilder构建新行。 与带+串联字符串相比,这样做效率更高,因为它可以最大程度地减少复制操作和内存分配。

在嵌套循环中,我们将单词和数字放在一起。

解决问题的一种优雅方法是利用C#中的String.Join方法。 我添加此答案是因为我是该方法的忠实拥护者,并认为它必须是此问题的某些答案的一部分,因为它与组合字符串有关。 这是我用来解决挑战的代码:

string[] firstInput = textBox1.Lines;
string[] secondInput = textBox2.Lines;
var combinedInputs = new string[firstInput.Length];
var combinedLine = new string[secondInput.Length];
for(int i = 0; i < firstInput.Length; i++)
{
    for(int j = 0; j < secondInput.Length; j++)
    {
        combinedLine[j] = firstInput[i] + secondInput[j];
    }
    //Combine all values of combinedLine with a '-' in between and add this to combinedInputs.
    combinedInputs[i] = String.Join("-", combinedLine);
}
outputTextBox.Lines = combinedInputs; //the resulting output

我希望这个答案也能有所帮助。 我想感谢Olivier解释文本框部分。 我想补充的另一件事是,这个答案并不是最有效的,而是易于阅读和理解的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM