简体   繁体   中英

How to include two text boxes texts?

I want to include two text box texts to one text box like this both of them are multiline. But I want special form of include, in other words I want to include them like this

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

Multiline textboxes return a string array with the lines in the Lines property. You could do something like this

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;

First we get the words and numbers arrays. Then we create a new array for the result. Since we want a result line for each word, we make it words.Length in size.

Then we loop through the words. We use a StringBuilder to build our new lines. This is more efficient as concatenation strings with + , as it minimizes copy operations and memory allocations.

In a nested loop we put the words and numbers together.

An elegant way to solve your issue is to make use of the String.Join method in C#. I'm adding this answer because I'm a big fan of the method and think it must be part of some answer to this question because it has to do with combining strings. Here's the code that I'd use to solve the challenge:

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

I hope this answer helped aswell. And I'd like to give credits to Olivier for explaining the textbox part. Another thing that I'd like to add is that this answer isn't meant to be the most efficient, but is meant to be easy to read and understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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