Insert a value in a specific line by index - c#

private void Parse_Click(object sender, EventArgs e)
{
for (int i = 0; i < keywordRanks.Lines.Length; i++)
{
int p = keywordRanks.Lines.Length;
MessageBox.Show(p.ToString());
string splitString = keywordRanks.Lines[i];
string[] s = splitString.Split(':');
for (int j = 0; j < keywords.Lines.Length; j++)
{
string searchString = keywords.Lines[j];
if (s[0].Equals(searchString))
{
richTextBox1.Lines[j] = searchString + ':' + s[1];
}
}
}
}
I have an issue with inserting string in a particular line. I have 2 multi line TextBoxes and one RichTextBox.
My application will search for the strings from textbox1 to textbox2 line by line and need to insert those matched values in a RichTextBox control but in the exact index position where it found in textbox2.
If the value found in 5th line of textbox2 then that found line need to be inserted in the RichTextBox 5th line.
Some how my code is not working. I tried a lot but no luck. The code I need something like below but its not working and an IndexOutOfBound exception is raised.
richTextBox1.Lines[j] = searchString + ':' + s[1];

Your RichTextBox must contain all the needed lines before you can set the value using the line index.
If the Control contains no text or line breaks (\n), no lines are defined and any attempt to set a specific Line[Index] value will generate an IndexOutOfRangeException exception.
Here, I'm using a pre-built array, sized as the number of possible matches (the Lines.Length of the keywords TextBox). All matches found are stored here in the original position. The array is then assigned to the RichTextBox.Lines property.
Note: directly using and pre-setting the RichTextBox.Lines won't have effect: the text will remain empty.
string[] MatchesFound = new string[keywords.Lines.Length];
foreach (string currentSourceLine in keywordRanks.Lines)
{
string[] SourceLineValue = currentSourceLine.Split(':');
var match = keywords.Lines.ToList().FindIndex(s => s.Equals(SourceLineValue[0]));
if (match > -1)
MatchesFound[match] = currentSourceLine;
}
richTextBox1.Lines = MatchesFound;
Source Matches Result
(keywordRanks) (keywords) (RichTextBox)
-------------------------------------------
aand:1 aand aand:1
cnd:5 this one
cnds:9 cnds cnds:9
fan:2 another one
gst:0 cnd cnd:5
fan fan:2

Related

C# Syntax - Remove last occurrence of ';' in string from split

I have a list of strings stored in an ArrayList. I want to split them by every occurrence of ';'. The problem is, whenever I try to display them using MessageBox, there's an excess space or unnecessary value that gets displayed.
Sample input (variable = a):
Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;
Below is a line of code I used to split them:
string[] display_document = (a[0] + "").Split(';');
Code to display:
foreach (object doc_properties in display_document)
{
TextBox aa = new TextBox();
aa.Font = new Font(aa.Font.FontFamily, 9);
aa.Text = doc_properties.ToString();
aa.Location = new Point(pointX, pointY);
aa.Size = new System.Drawing.Size(80, 25);
aa.ReadOnly = true;
doc_panel.Controls.Add(aa);
doc_panel.Show();
pointY += 30;
}
The output that displays are the following:
How do I remove the last occurrence of that semicolon? I really need help fixing this. Thank you so much for all of your help.
Wouldnt It be easiest to check if the input ends with a ";" before splitting it, and if so remove the last character? Sample code:
string a = "Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
if (a.EndsWith(";"))
{
a = a.Remove(a.LastIndexOf(";"));
}
//Proceed with split
Split will not print last semicolon if no space character is added and your input is a string.
I don't know why you prefer an array list (which probably is the reason of this strange behaviour) but if you could use your input as a string you could try that
string a = "Arial;16pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
string[] display_document = a.Split(';');
foreach (object doc_properties in display_document)
{
//The rest of your code
}

Splitting a string seems not to work

I have problems with reading a file (textasset) line by line and getting the results!
Here is the file I am trying to read:
AUTHOR
COMMENT
INFO 1 X ARG 0001 0.581 2.180 1.470
INFO 2 X ARG 0001 1.400 0.974 1.724
INFO 3 X ARG 0001 2.553 0.934 0.751
INFO 4 X ARG 0001 3.650 0.494 1.053
INFO 5 X ARG 0001 1.188 3.073 1.532
INFO 6 X ARG 0001 2.312 1.415 -0.466
INFO 7 X ARG 0001 -0.232 2.249 2.180
END
Here is the code I am using:
//read file
string[] line = file.text.Split("\n"[0]);
for(int i = 0 ; i < line.Length ; i++)
{
if(line[i].Contains("INFO"))
{
//To replace all spaces with single underscore "_" (it works fine)
string l = Regex.Replace(line[i]," {2,}","_");
//In this Debug.Log i get correct results
//For example "INFO_1_X_ARG_0001_0.581_2.180_1.470"
Debug.Log(l);
string[] subline = Regex.Split(l,"_");
//Only for first "INFO" line i get correct results (INFO,1,X,ARG,0001,0.581,2.180,1.470)
//For all other "INFO" lines i get incomplete results (first,fourth and fifth element are not put into substrings
//like they are dissapeard!
foreach(string s in subline){Debug.Log(s);}
}
}
Explanation:
I first split text into lines (works fine),then i read only lines that contain INFO
I loop all lines that contain INFO and replace all spaces with underscore _ (this works fine)
I split lines that contain INFO into substrings based on underscore _
When I print out the lines only first line with INFO seems to have all substrings
every next line is not splitted correctly (first part INFO is omitted as well as third string)
It seems very unreliable. Is this the way to go with these things? Any help is appreciated! This should be simple, what i am doing wrong?
EDIT:
Something is wrong with this code (it should be simple, but it does not work)
Here is the updated code (i just made a List<string> list = new List<string>() and copied all substrings. I use unity3D so that list contents show in the inspector. I was shocked when i so all properly extracted substrings but simple
foreach(string s in list)
Debug.Log(s);
was indeed missing some values. so I was trying different things and this code:
for(int x = 0; x < list.Count ; x++)
{
Debug.Log("List: " + x.ToString() + " " + list[x].ToString());
}
shows contents of the list properly, but this code (note that i just removed x.ToString()) is missing some elements in the list. It does not want to read them!
for(int x = 0; x < list.Count ; x++)
Debug.Log("List: " + list[x].ToString());
So i am not sure what is going on here?!
There are some problems
1>The contains method you are using is case sensitive i.e INFO != info
You should use
line[i].ToLower().Contains("info")
2>Is the text always separated by space.it may also be separated by tabs.you are better off with
Regex.Replace(line[i]," {2,}|\t+","_");
//this would replace 1 to many tabs or 2 or more space
The following seems to be working for me:
using (var fs = new FileStream(filePath, FileMode.Open))
using (var reader = new StreamReader(fs))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("INFO"))
{
line = Regex.Replace(line, "[ ]+", "_");
var subline = line.Split('_');
foreach (var str in subline)
{
Console.Write("{0} ",str);
}
Console.WriteLine();
}
}
}
You may want to try something like this:
for (int i = 0; i < line.Length; i++)
{
if (line[i].Contains("INFO"))
{
string l = Regex.Replace(line[i], #"\p{Zs}{2,}|\t+", "_");
string[] sublines = l.Split('_');
// If you want to see the debug....
sublines.ForEach(s => Debug.Log(s));
}
}
The \p{Zs} will match all Unicode separator/space characters (e.g. space, non-breaking spaces, etc.). The following reference may be of some help to you: Character Classes in Regular Expressions.
Try string.split("\t"[0]") You have probable tabulators between columns.

getting current line text is on

I have a list of lines that looks like this:
textbox.text += "p"+b+" the rest\r\np"+b+" more text";
b is supposed to represent the current line number in the textbox that the line is on. I have tried using textbox.lines.count() but it only changes i into the last line number.
Is there any other way about going with this, or do I have to switch to another method?
If you are assigning, I think you can do it manually (calculate the line number). There is no function that could "guess" on which line the tex will appear.
You can create a integer variable and increment it when appending a line/s and use the variable when you need to display the current line number.
I split the lines by the line breaks ("\r\n") and used a for loop to replace "b" (I changed it to string rather than a variable)
for (int i = 0; i < da.Length; i++)
{
//replace char with number
string f = da[i].Replace("n", (i + 1).ToString());
disp.Text += f + "v";
}
I added "v" so that I can replace it outside of the loop with "\r\n" again.

C# - Addition on a string and replace with new string

If I have a RichTextBox that is loaded from a file containg:
TEXT MORETEXT 10.505 100.994 0
TEXT MORETEXT -5.132 -12.994 90
TEXT MORETEXT 100.001 -8.994 270
and a TextBox that contains whatever the user enters in the textbox. Let's say the user enters "10.005".
My question is, how do I take this value and add it to the 3rd column containing the values 10.505, -5.132, 100.001. Once it is added, I would like to take the value and Replace the old value in the string. SO the updated RichTextBox would look like this.
TEXT MORETEXT 20.510 100.994 0
TEXT MORETEXT 4.873 -12.994 90
TEXT MORETEXT 110.006 -8.994 270
RIGHT NOW I am able to strip the strings from the RichTextBox by using this code:
private void calculateXAndYPlacementTwo()
{
// Reads the lines in the file to format.
var fileReader = File.OpenText(filePath);
// Creates a list for the lines to be stored in.
var fileList = new List<string>();
// Adds each line in the file to the list.
while (true)
{
var line = fileReader.ReadLine();
if (line == null)
break;
fileList.Add(line);
}
// Creates new lists to hold certain matches for each list.
var xyResult = new List<string>();
var xResult = new List<string>();
var yResult = new List<string>();
// Iterate over each line in the file and extract the x and y values
fileList.ForEach(line =>
{
Match xyMatch = Regex.Match(line, #"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)");
if (xyMatch.Success)
{
// grab the x and y values from the regular expression match
String xValue = xyMatch.Groups["x"].Value;
String yValue = xyMatch.Groups["y"].Value;
// add these two values, separated by a space, to the "xyResult" list.
xyResult.Add(String.Join(" ", new[]{ xValue, yValue }));
// Adds the values into the xResult and yResult lists.
xResult.Add(xValue);
yResult.Add(yValue);
// Place the 'X' and 'Y' values into the proper RTB.
xRichTextBox.AppendText(xValue + "\n");
yRichTextBox.AppendText(yValue + "\n");
}
});
}
To get the values in the xRichTextBox looking like:
10.505
-5.132
100.001
and the yRichTextBox looking like:
100.994
-12.994
-8.994
But I do not know how to turn those into values that can have addition used on them...
EDIT:
I have messed around with this some more... I am now using this code (below) to try to accomplish what I need it to do. This is only for the "X" (3rd column).
HOWEVER THIS CODE IS NOT WORKING (it concats the user input to the end of the xRichTextBox instead of mathematically adding it to each line..)
The xDisplacementTextBox is the user input and the xRichTextBox is the stripped values from the main string.
StringBuilder stringBuilder = new StringBuilder();
string[] Lines = xRichTextBox.Text.Split('\n');
double d = double.Parse(xDisplacementTextBox.Text);
for(int i = 0; i < Lines.Length; ++i)
{
string newThing = double.Parse((Lines[i]) + d).ToString();
stringBuilder.AppendLine(newThing);
}
xRichTextBox.Text = stringBuilder.ToString();
This is also not letting me enter in values that have decimals (ie. 50.005)..
Look at double.Parse - as in
double x = double.Parse(xValue);
To expand, and do your work for you...
double d = double.Parse(xDisplacementTextBox.Text);
string[] Lines = xRichTextBox.Text.Split('\n');
for(int i = 0; i < Lines.Length; ++i)
{
Match lineMatch = Regex.Match(lines[i], #"^(?<p>.*)(?<x>-?\d+\.\d+)(?<y>\s+-?\d+\.\d+\s+-?\d+\.\d+)$");
if (lineMatch.Success)
{
double xValue = double.Parse(lineMatch.Groups["x"].Value) + d;
lines[i] = lineMatch.Groups["p"] + xValue + lineMatch.Groups["p"];
}
}
xRichTextBox.Text = string.Join(lines, '\n');
Too many strings and not enough data structures.
This looks like a data structure:
TEXT MORETEXT 10.505 100.994 0
TEXT MORETEXT -5.132 -12.994 90
TEXT MORETEXT 100.001 -8.994 270
So, create a class that holds
"Text" string
"MoreText" string
10.505 - double (let's call this prop1)
100.994 - double
0 - int
I'm speculating on the data values here.
Load the List<> of your class into memory.
Then, apply the text box value to your list of object every time the value changes.
PsuedoCode:
foreach(class c in List<>)
{
c.prop1 = c.prop1 + (double)Textbox.value;
}
Override ToString() in your class and display the object as needed in the rich text box.
Personally I would use a list box to display the objects.

C# writing out text files matching listbox and contents of another text file

I have a file created from a directory listing. From each of item a user selects from a ListBox, the application reads the directory and writes out a file that matches all the contents. Once that is done it goes through each item in the ListBox and copies out the item that matches the ListBox selection. Example:
Selecting 0001 matches:
0001456.txt
0001548.pdf.
The code i am using isn't handling 0s very well and is giving bad results.
var listItems = listBox1.Items.OfType<string>().ToArray();
var writers = new StreamWriter[listItems.Length];
for (int i = 0; i < listItems.Length; i++)
{
writers[i] = File.CreateText(
Path.Combine(destinationfolder, listItems[i] + "ANN.TXT"));
}
var reader = new StreamReader(File.OpenRead(masterdin + "\\" + "MasterANN.txt"));
string line;
while ((line = reader.ReadLine()) != null)
{
for (int i = 0; i < listItems.Length; i++)
{
if (line.StartsWith(listItems[i].Substring(0, listItems[i].Length - 1)))
writers[i].WriteLine(line);
}
}
Advice for correcting this?
Another Sample:
I have 00001 in my listbox: it returns these values:
00008771~63.txt
00002005~3.txt
00009992~1.txt
00001697~1.txt
00000001~1.txt
00009306~2.txt
00000577~1.txt
00001641~1.txt
00001647~1.txt
00001675~1.txt
00001670~1.txt
It should only return:
00001641~1.txt
00001647~1.txt
00001675~1.txt
00001670~1.txt
00001697~1.txt
Or if someone could just suggest a better method for taking each line in my listbox searching for line + "*" and whatever matches writes out a textfile...
This is all based pretty much on the one example you gave, but I believe the problem is that when you are performing your matching, you are getting the substring if your list item value and chopping off the last character.
In your sample you are attempting to match files starting with "00001", but when you do the match you are getting substring starting at zero and value.length-1 characters, which in this case would be "0000". For example:
string s = "00001";
Console.WriteLine(s.Substring(0,s.Length-1));
results in
0000
So I think if you just changed this line:
if (line.StartsWith(listItems[i].Substring(0, listItems[i].Length - 1)))
writers[i].WriteLine(line);
to this
if (line.StartsWith(listItems[i]))
writers[i].WriteLine(line);
you would be in good shape.
Sorry if I misunderstood your question, but let's start with this:
string line = String.Empty;
string selectedValue = "00001";
List<string> matched = new List<string>();
StreamReader reader = new StreamReader(Path.Combine(masterdin, "MasterANN.txt"));
while((line = reader.ReadLine()) != null)
{
if(line.StartsWith(selectedValue))
{
matched.Add(line);
}
}
This will match all lines from your MasterANN.txt file which begins with "00001" and add them into a collection (later we'll work on writing this into a file, if required).
This clarifies something?

Categories

Resources