I have a Single line text box and Multiline text box, and want to include a word into the Single line text box with the words in Multiline text box per line
Like this :
Single line text: "Hello"(I have to use variables)<br>
Multiline words:
<br>
1998<br>
1999<br>
2000
Expected results:
Hello1998
Hello1999
Hello2000
Pls Help me
I use the below code, but it is not working just with the Single line text box and I have to manipulate by both text boxes:
string left = string.Format(add.Text , Environment.NewLine);
string right = string.Format(textBox1.Text, Environment.NewLine);
string[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string output = "";
if (leftSplit.Length == rightSplit.Length)
{
for (int i = 0; i < leftSplit.Length; i++)
{
output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;
}
}
result.Text = output;
Could you please advise me on the right approach?
If you have single line only one word, then no need split it into an array.
Lets consider it as a string left = "Hello";
and textbox1 contains multiline words i.e.
string right = string.Format(textBox1.Text, Environment.NewLine); // right variable contains 1998 \n 1999 \n 2000
Then you can try below approach
var concatString = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Select(x => left + x);
string result = string.Join(Environment.NewLine , concatString);
.Net Fiddle
Output :
Hello1998
Hello1999
Hello2000
TextBox.GetLineText(int) will help you:
var singlelineText = singlelineTextBox.Text;
var composedLines = new List<string>();
for (var i = 0; i < multilineineTextBox.LineCount; i++)
{
composedLines.Add(singlelineText + multilineineTextBox.GetLineText(i));
}
result.Text = string.Join(EnvironmentNewline, composedLines);
Related
I am trying to making a simple tool Windows form app, that I can paste a list of 200 X,Y coordinates and then I can click a button and the tool will output a text file with a command on each line that will have the X,Y coordinates in it.
the input looks like this:
65737,163129
-21687,-27399
164089,50153
164649,63465
-28663,140057
-28951,110329
149833,-30231
and the output should look something like this:
waypoint:WLM 1:1:78168:~:1560:1:true:0:gui.xaero_default:false:0:false
waypoint:WLM 2:2:919432:~:154200:11:true:0:gui.xaero_default:false:0:false
waypoint:WLM 3:3:791080:~:15624:0:true:0:gui.xaero_default:false:0:false
waypoint:WLM 4:4:79288:~:16968:6:true:0:gui.xaero_default:false:0:false
waypoint:WLM 5:5:79064:~:155702:9:true:0:gui.xaero_default:false:0:false
This is what I have so far, I was able to parse the input into a array but now i have no idea how to combine it and save it as a text file.
private void button2_Click(object sender, EventArgs e)
{
var lines = richTextBox1.Text.Split((new char[] { ',' }), StringSplitOptions.RemoveEmptyEntries);
foreach (var s in lines)
{
string[] result = lines.ToArray();
outputwindow.Text = String.Join("\n", result); // parse string so they are all on new lines ( they are still in the array as one tho)
var cords = outputwindow.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); // we split the data again and now the result is cords by them selves
foreach (var c in cords)
{
string[] cordstoarray = cords.ToArray(); // cordstoarry should now be the proper data set
//waypoint:name:initials:x:y:z:color:disabled:type:set:rotate_on_tp:tp_yaw:global
decimal startnumb = startingnumberb.Value;
// wc[1] + wc[0] + name + wc[0] + inl + wc[0] + cordstoarray[0] + wc[0] + wc[3] + wc[0] + cordstoarray[1] + wc[0] + wc[4]
for (int i = 0; i < cordstoarray.Length; i++)
{
string[] buildwaypoints = new string[13];
string[] wc = { ":", "waypoint", "~", "1:false:0:gui.xaero_default:false:0:false" };
string name = nametextbox.Text; // get the name
string inl = initialstextbox.Text; // get the initials
buildwaypoints[i] = { wc[1] , wc[0] , name , wc[0] , inl , wc[0] , cordstoarray[i] , wc[0] , wc[3] , wc[0] , cordstoarray[i + 1] , wc[0] , wc[4]}; // Build wapypoint array
File.WriteAllLines("Triwaypt.txt", buildwaypoints);
using (StreamReader sr = new StreamReader("Triwaypt.txt"))
{
string res = sr.ReadToEnd();
Console.WriteLine(res);
}
}
}
}
}
you can use File.WriteAllLines() - but in a slightly different way
first add List<string> outputLines = new List<string>(); to the start of your program (just after var lines = ...), so that you can start saving your generated lines (or you can use File.AppendAllText if you want to save memory)
Then when you generate your buildWayPoints array - just generate a string to add to the list instead. Something like
outputLines.Add($"{wc[1]}{wc[0]}{name}{wc[0]}{inl}{wc[0]}{cordstoarray[i]}{wc[0]}{wc[3]}{wc[0]}{cordstoarray[i + 1]}{wc[0]}{wc[4]}");//assuming your code up to this point was correct, also you can replace the {wc[n]} with the literal text if you feel like it
Should work, but I'd definitely reccomend cleaning up the code around that section. Finally after the loop is finished you need to write your new list of lines to file with something like File.WriteAllLines(#"Filepath", outputLines)
Assuming your question revolved around creating the output file, the above should work perfectly, if your question was actually about properly formatting the input you'd need to explain your logic a bit more clearly - but as a stab in the dark
counter++;//define counter as int counter = 0; earlier
var twoCords = c.Split(',');
var outputLine = $"waypoint:WLM {counter}:{counter}:{c[0]}:~:{c[1]}:{idk about this one sorry}:true:0:gui.xaero_default:false:0:false";
p.s. one immediate bug I need to mention is you did a foreach(var c in cords) but then you reference cords instead of c in your code
ive got the following c# code:
string textBoxInput = richTextBox1.Text;
StreamReader SentencesFile = new StreamReader(#"C:\Users\Jeroen\Desktop\School\C#\opwegmetcsharp\answersSen.txt");
string Sentence = SentencesFile.ReadLine();
List<List<string>> keywordsList = new List<List<string>>();
List<string> outputSentence = new List<string>();
while (Sentence != null)
{
string keywords = Sentence.Substring(0, Sentence.IndexOf(' '));
string sentenceString = Sentence.Substring(0, Sentence.IndexOf(' ') +1);
List<string> splitKeyword = keywords.Split(',').ToList();
keywordsList.Add(splitKeyword);
outputSentence.Add(sentenceString);
}
int similar = 0;
int totalSimilar = 0;
List<string> SplitUserInput = textBoxInput.Split(' ').ToList();
And a .txt file which contains the following:
car,bmw Do you own a BMW?
car,Tesla Do you own a Tesla?
new,house Did you buy a new house?
snow,outside Is it snowing outside?
internet,down Is your internet down?
I can't figure out how i can compare every word that a user typed in the input (richTextBox1.Text) with the keywords in the .txt file ( like car and bmw for the first sentence )
And it also has to remember the sentence that has the highest amount of "hits".
I'm really stuck and searched a lot, but somehow i can't find out how i can do this.
A lot of thanks in advance!
You can use the LINQ Contains to check if a word is found in a list. But beware because it is case sensitive as password does. Use it like this:
//assuming you already list the keyword here
List<string> keywords = new List<string>() { "keyword1", "keyword2" };
Then for each sentence, supposing in this form:
string sentence1 = "Hi, this keYWord1 present! But quite malformed";
string sentence2 = "keywoRD2 and keyWOrd1 also present here, malformed";
Note: the above sentences could be your text from RichTextBox or file, it doesn't matter. Here I only show the concept.
You can do:
string[] words = sentence1.ToLower().Split(new char[] { ' ', ',', '.' });
int counter = 0;
for (int i = 0; i < words.Length; ++i){
counter += keywords.Contains(words[i]) ? 1 : 0;
}
And you can do likewise for sentence2. Whoever gets the highest counter has the highest hits.
This might be too advanced for a 1st year student but this piece of code will work for your need. Using Regex class to do matching for you. Performance-wise it's faster (AFAIK). I used a console application to work on this as I don't think it will be hard for you to use it in a WinForms/WPF application.
string textBoxInput = "car test do bmw"; // Just a sample as I am using a console app
string[] sentences = File.ReadAllLines("sentences.txt"); // Read all lines of a text file and assign it to a string array
string[] keywords = textBoxInput.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Split textBoxInput by space
int[] matchArray = new int[sentences.Length];
for(int i = 0; i < sentences.Length; i++)
{
Regex regex = new Regex(#"\b(" + string.Join("|", keywords.Select(Regex.Escape).ToArray()) + #"+\b)", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(sentences[i]);
matchArray[i] = matches.Count;
}
int highesMatchIndex = Array.IndexOf(matchArray, matchArray.OrderByDescending(item => item).First());
Console.WriteLine("User input: " + textBoxInput);
Console.WriteLine("Matching sentence: " + sentences[highesMatchIndex]);
Console.WriteLine("Match count: " + matchArray[highesMatchIndex]);
Console.ReadLine();
I have a text file who are like this :
Rows
...
product.people
product.people_good
product.people_bad
product.boy
#product.me
...
Rows
I want to put # before product. and the file to be :
Rows
...
#product.people
#product.people_good
#product.people_bad
#product.boy
#product.me
...
Rows
For this I use next code :
string installerfilename = pathTemp + fileArr1;
string installertext = File.ReadAllText(installerfilename);
var linInst = File.ReadLines(pathTemp + fileArr1).ToArray();
foreach (var txt in linInst)
{
if (txt.Contains("#product="))
{
installertext = installertext.Replace("#product=", "product=");
}
else if (txt.Contains("product.") && (!txt.StartsWith("#")))
{
installertext = installertext.Replace(txt, "#" + txt);
}
File.WriteAllText(installerfilename, installertext);
}
But this code do the next thing:
Rows
...
#product.people
##product.people_good
##product.people_bad
#product.boy
#product.me
...
Rows
Someone can explain me way ? And how I can write just one # before that rows?
Currently you're reading the same text file twice - ones as individual lines and once as a whole thing. You're then rewriting a file as many times as you have lines. This is all broken. I suspect you simply want:
// Note name changes to satisfy .NET conventions
// Note: If pathTemp is a directory, you should use Path.Combine
string installerFileName = pathTemp + fileArr1;
var installerLines = File.ReadLines(installerFileName)
.Select(line => line.StartsWith("product=") ? "#" + line : line)
.ToList();
File.WriteAllLines(installerFileName, installerLines);
If you were writing to a different file than the one you were reading from, you wouldn't need the ToList call.
You can split by product, and then concatenate it to a new string :
// string installerFileText = File.ReadAllText(installerFileName);
string installerFileText = #"
Rows
...
product.people
product.people_good
product.people_bad
product.boy
...
Rows";
string[] lines = installerFileText.Split(new string[] { "product." }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.Length; i++)
sb.Append(((i > 0 && i < lines.Length) ? "#product." : "") + lines[i]);
// File.WriteAllText(installerFileName, sb.ToString());
Console.WriteLine(sb.ToString());
Console.ReadKey();
Output:
Rows
...
#product.people
#product.people_good
#product.people_bad
#product.boy
...
Rows";
else if (txt.Contains("product.") && (!txt.StartsWith("#")))
{
installertext = installertext.Replace(txt, "#" + txt);
}
Why don't your replace the "!txt.StartsWith("#")" by a "!txt.Contains("#")" ?
Think that would do the trick !
I have a rich text box in which i am triggering the keypress event with spacebar. The logic to find number of all occurrences of the last written word which i have implemented is:
private void textContainer_rtb_KeyPress_1(object sender, KeyPressEventArgs e)
{
//String lastWordToFind;
if (e.KeyChar == ' ')
{
int i = textContainer_rtb.Text.TrimEnd().LastIndexOf(' ');
if (i != -1)
{
String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
}
}
}
But its not working. Can somebody please point out the error or rectify it?
regex doesn't work lilke this:
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
this part:
this.textContainer_rtb.Text.Split(' ').ToString()
will split your text into array of strings:
string s = "sss sss sss aaa sss";
string [] arr = s.Split(' ');
arr is like this after split:
arr[0]=="sss"
arr[1]=="sss"
arr[2]=="sss"
arr[3]=="aaa"
arr[4]=="sss"
then ToString() returns type name:
System.String[]
So what you're really doing is:
int count = new Regex("ccc").Matches("System.String[]").Count;
That's why it doesn't work. You should simply do:
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text).Count;
You Regex appears to be incorrect. Try the following.
String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();
// Match only whole words not partial matches
// Remove if partial matches are okay
lastWordToFind = #"\b" + word + #"\b";
Console.WriteLine(Regex.Matches(richTextBox1.Text, word).Count);
How do I remove more than three spaces from each line and end the string right there to look the line on the right using c#?
[Example1]
PO BOX XXX OVERDUE - PAY NOW
then transform to
PO BOX XXX
[Example2]
ClientB AMOUNT CARRI
then transform to
ClientB
[Example3]
PO BOX 400 FORWARD TO N
then transform to
PO BOX 400
var firstColumn = origString.SubString(0, origString.IndexOf(" "));
input = "PO BOX XXX OVERDUE - PAY NOW ";
input = input.Remove(input.IndexOf(" "));
there are 3 spaces in the indexOf paranthesis
Or you can do a split if you dont know if there is a tab or space -
input = input.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)[0];
You can do this:
var input = new string[3] { "PO BOX XXX OVERDUE - PAY NOW ",
"ClientB AMOUNT CARRI",
"PO BOX 400 FORWARD TO N "
};
for (int x = 0, len = input.Length; x != len; x++)
{
input[x] = Regex.Replace(input[x], #"\s{3}[^\n]+", string.Empty);
}
//input is ["PO BOX XXX","ClientB","PO BOX 400"]
Using linq:
var output = input.Select(str => Regex.Replace(str, #"\s{3}[^\r\n]+$", string.Empty));
if you're reading this string from file, you can do this:
var file = #"D:\file.txt";
var lines = File.ReadAllLines(file);
var output = lines.Select(str => Regex.Replace(str, #"\s{3}[^\n]+$", string.Empty)); // is ["PO BOX XXX","ClientB","PO BOX 400"]
You can use the string.Split method which results the string[]. Basing on the array count you can take the elements u need.
string base string = "PO BOX XXX OVERDUE - PAY NOW";
string[] delimittedStringArray = baseString.Split(' ');
if(delimittedStringArray.Length > 3)
{
// Take the data from array
}
else
{
// Do what ever
}
// I am not sure whether it is Length or Count in the if condition.