簡體   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