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.
Related
I got an idea that i wanted to make today but ran into the problem that i have a string variable with paragraph, but i need an Array of single lines. So I tried to do this with the String.Substring and the String.IndexOf functions but this only worked kinda because i dont exactly know how VisualStudio handels the Index of Paragraphs and how strings work with paragraphs because i just learned C# this year.
I tried it in Windows-Forms btw.
Can anyone tell me how index's with paragraphs work or especialy how to use them correctly.
This is the code i tried which only works for the 1st line and works kinda with the 2nd but not with any further
string input_raw;
string[] input = new string[100];
int index_zeile = 0;
int x = 0, y = 0;
input_raw = input_text_box.Text;
for (int i = 0; i < 100; i++)
{
if (i == 0)
{
y = input_raw.IndexOf(";");
input[i] = input_raw.Substring(index_zeile, y);
x = y + 1;
}
else
{
index_zeile = input_raw.IndexOf(";", x);
input[i] = input_raw.Substring(x, index_zeile-3);
x = x + index_zeile;
}
}
I wish you entered your text input, but you can split the string into an array. The following code assigns a multi-line string to an array.
string[] lines = input_text_box.Text.Split('\n');
Hi sorry guys I'm pretty new to C# and programming in general.
I have a text file that I'm reading from which contains 10 lines (all but the first of which are relevant).
I want to split each line (besides the first since it's only one word) by the commas, then retrieve the 5th one along of each line, adding it to a total.
Currently all I have been able to do is essentially split and add the same value to the total 10 times, instead of adding the 9 different values together, or face a "System.IndexOutOfRangeException".
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 0; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[4];
int vvint = int.Parse(vehicleValue);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
As it stands, the above code results in a "System.IndexOutOfRangeException" highlighting "vehicleValue = bits [4];"
Every line of the file looks like this, besides the first one.
Car,Ford,GT40,1964,250000,987,Red,A1,2,4,FALSE
The value I want out of this specific line would be '250000' - the 5th one along. I'm trying to get the 5th one along from every line.
Your problem is that you are trying to parse also the first line (which does not contain enough entries so you get the exception). You can skip the first line by starting your iteration at index 1:
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 1; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[4];
int vvint = int.Parse(vehicleValue);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
bits[4] is the fifth item in the array as indexing starts from zero, to get the fourth item you should get bits[3]
int totalValues = 0;
string[] larray = lines.ToArray(); //create array from list
string vehicleValue;
for (int i = 0; i < larray.Length; i++)
{
string[] bits = larray[i].Split(',');
vehicleValue = bits[3];
int vvint = int.Parse(bits[3]);
totalValues = totalValues + vvint;
}
totalValue.Text = totalValues.ToString();
Hi guys, so I need to add a 'space' between each character in my displayed text box.
I am giving the user a masked word like this He__o for him to guess and I want to convert this to H e _ _ o
I am using the following code to randomly replace characters with '_'
char[] partialWord = word.ToCharArray();
int numberOfCharsToHide = word.Length / 2; //divide word length by 2 to get chars to hide
Random randomNumberGenerator = new Random(); //generate rand number
HashSet<int> maskedIndices = new HashSet<int>(); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
for (int i = 0; i < numberOfCharsToHide; i++) //counter until it reaches words to hide
{
int rIndex = randomNumberGenerator.Next(0, word.Length); //init rindex
while (!maskedIndices.Add(rIndex))
{
rIndex = randomNumberGenerator.Next(0, word.Length); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
}
partialWord[rIndex] = '_'; //replace with _
}
return new string(partialWord);
I have tried : partialWord[rIndex] = '_ ';however this brings the error "Too many characters in literal"
I have tried : partialWord[rIndex] = "_ "; however this returns the error " Cannot convert type string to char.
Any idea how I can proceed to achieve a space between each character?
Thanks
The following code should do as you ask. I think the code is pretty self explanatory., but feel free to ask if anything is unclear as to the why or how of the code.
// char[] partialWord is used from question code
char[] result = new char[(partialWord.Length * 2) - 1];
for(int i = 0; i < result.Length; i++)
{
result[i] = i % 2 == 0 ? partialWord[i / 2] : ' ';
}
return new string(result);
Since the resulting string is longer than the original string, you can't use only one char array because its length is constant.
Here's a solution with StringBuilder:
var builder = new StringBuilder(word);
for (int i = 0 ; i < word.Length ; i++) {
builder.Insert(i * 2, " ");
}
return builder.ToString().TrimStart(' '); // TrimStart is called here to remove the leading whitespace. If you want to keep it, delete the call.
I have a problem with C#.
I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again.
Now I don't know how to navigate through the file (forward and backward) to the line I want.
Can anybody help?
You can do something like this:
var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
//Find the word the first time
if(!foundFirstTime && text[i].Contains("word"))
{
//Skip 3 lines - and continue
i = Math.Min(i+3, text.Length-1);
foundFirstTime = true;
}
if(foundFirstTime && text[i].Contains("word"))
{
//Do whatever!
}
}
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
select lines).ToList<string>();
for (int i = 0; i < query.Count; i++)
{
if (query[i].Contains("TextYouWant"))
{
i = i + 3;
}
}
Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:
string[] lines = System.IO.File.ReadAllLines("File.txt");
int skip = 3;
string word = "foo";
string pattern = string.Format("\\b{0}\\b", word);
for (int i = 0; i < lines.Count(); i++)
{
var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);
System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));
if (match) i += skip;
}
If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.
I want to split the given string and remove the duplicate from that string. Like I have following string:
This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question.
Now I want to split that whole string with white space and that new array will did not have duplicate entry.
How can I do this?
"This is my first post in stack overflow, I am very new in development and I did not have much more idea about the how to post the question."
.Split() // splits using all white space characters as delimiters
.Where(x => x != string.Empty) // removes an empty string if present (caused by multiple spaces next to each other)
.Distinct() // removes duplicates
Distinct() and Where() are LINQ extension methods, so you must have using System.Linq; in your source file.
The above code will return an instance of IEnumerable<string>. You should be able to perform most operations required using this. If you really need an array, you can append .ToArray() to the statement.
add the array into a HashSet<String>, this would remove the duplicates.
here is Micorosft documentation on HashSet..
static void Main()
{
string str = "abcdaefgheijklimnop";
char[] charArr = str.ToCharArray();
int lastIdx = 0;
for (int i = 0; i < str.Length;)
{
for (int j = i + 1; j < str.Length - 1; j++)
{
if (charArr[i] == charArr[j])
{
//Console.WriteLine(charArr[i]);
int idx = i != 0 ? i - 1 : i;
lastIdx = j;
string temp = str.Substring(idx, j - idx);
Console.WriteLine(temp);
break;
}
}
i++;
}
Console.WriteLine(str.Substring(lastIdx));
}