Comparing string array with starting values in another - c#

I have a string array with fixed values and a richtextbox whose text is dynamically changed. Some of the lines in the richtextbox start with values in the string array. I want to select only the lines of the richtextbox which do not start with values in the string array.
The following code returns all lines in the richtextbox.
string[] parts = new string[] { "Definition:", "derivation:", "derivations:"};
IEnumerable<string> lines = richTextBox1.Lines.Where(
c =>parts.Any(b=>!c.StartsWith(b)));
My question is: How can I select only the lines of the richtextbox which do not start with values in the string array?

Change Any to All. As it's written, it returns all lines because a line can't start with more than one word.
Your current code says, "return true if there is any word in parts that isn't the first word of the line." Obviously, the line can't start with "foo" and with "derivation:". So you always get true.
You want to say, "return true if all of the words in parts are not the first word of the line."
Another way to do it is:
lines = richTextBox1.Lines.Where(c => !parts.Any(b => c.StartsWith(b)));
Which is probably how I would have written it.

You put the (!) operator in the wrong place. If you want to use Any then
string[] parts = new string[] { "Definition:", "derivation:", "derivations:"};
IEnumerable<string> lines = richTextBox1.Lines.Where(
c => !parts.Any(b => c.StartsWith(b)));

Related

How to delimit strings in each line of a text file and compare them to a user input

My goal is to match the users input into a field with data in a text file.
1000|I-002096.02.02|EL|MISCMI
1000|I-002097.02.02|EL|ESYEED
1000|I-002098.02.02|EL|MISCCA
1000|I-002099.02.02|EL|MISCCA
1000|I-002100.02.02|EL|MISCCA
1000|I-002101.02.02|EL|USQUIC00
1000|I-002102.02.02|EL|MISCMI
The portion after the first "|" delimiter is what I need to check against the users input. (users input is stored in TxtWBS.Text in the code below)
This is what I have tried but this only works when each line has nothing to delimit.
string[] wbslist = File.ReadAllLines(filePath);
bool wbsExists = Array.Exists(wbslist, element => element == TxtWBS.Text);
if (wbsExists)
/*leave empty*/;
else
errMessage += "This WBS does not exist" + Environment.NewLine;
I expect to be able to check if the users input exists in the text file.
This could be done with a single line in Linq.
Change your test to:
bool wbsExists = wbslist.Any(x => x.Contains(TxtWBS.Text));
And if you are not sure about the case of the input you can have
bool wbsExists = wbslist.Any(x => -1 != x.IndexOf(TxtWBS.Text, StringComparison.CurrentCultureIgnoreCase));
More, if you want to check an exact match against the second item in the line then
bool wbsExists = wbslist.Select(x => x.Split('|')[1]).Any(k => k == TxtWBS.Text);
Consider also to change the loading of your text data to
var wbslist = File.ReadLines(filePath);
File.ReadLines doesn't read all the lines in memory immediately but returns an IEnumerable<String> that is more suited in Linq expressions
You can use the following code. Read file and iterate line by line, splitting each line into array of strings by token '|'.
string[] wbslist = File.ReadAllLines(filePath);
foreach(string line in wbslist)
{
string [] splittedLine = line.Split('|');
// I assume you need the second element in the delimited line
if(string.Equals(splittedLine[1], TxtWBS.Text, StringComparison.OrdinalIgnoreCase))
Console.WriteLine("Website found");
}
Well, if you're absolutely sure about the format of the file then you can split each line on the delimiter and check the user input against the second element in the resulting array.
bool wbsExists = Array.Exists(wbslist, element => element.Split('|')[1] == TxtWBS.Text);

I want to split a string after a period and put that sentence onto a separate line

I want to take user input then separate the string after each period. Then I want to put each sentence onto their own line in a text box in Visual Studio.
I know how to store the sentences in an array, and put each sentence on every other line but when I run, the outcome for every letter I type is system.string[].
string input = TextEditor.Text;
string[] tokens = input.Split('.');
Output.AppendText(Environment.NewLine);
Output.Text += tokens;
I am pretty sure it is coming from the output.text = token;, but I don't know what to replace that with. Any idea?
You should simply use string.Join
string input = TextEditor.Text;
string[] tokens = input.Split('.');
Output.Text = string.Join(Environment.NewLine, tokens);
You can even achieve your goal within a single line
Output.Text = string.Join(Environment.NewLine, TextEditor.Text.Split('.'));
or use string.Replace with (not sure if it is faster)
Output.Text = TextEditor.Text.Replace(".", Environment.NewLine));
Your current code fails because you add the array, not the individual string elements of the array. Instead string.Join joins the individual elements of the array with the separator specified as first parameter.
Remember however that to display multiple lines of text you need to have your textbox with enough height space and with the property Multiline set to True.

Filter a string variable from a file and change it

I am currently working on a basic program but I'm having trouble selecting the string variables. All the variables begin with _ and then a relevant string of words follow.
First, you don't need to read the whole file and save it again inside the loop that goes through each line, you can instead do all your replacements then save once.
For replacement, you can use regular expression replacement. I'm not sure what kind of transformation you're looking to do on the text, but you can do something like the following (in this example I'm just transforming text to upper case):
string[] textLines = File.ReadAllLines(#"c:\Users\Darren\Desktop\Hello.txt");
var results = new List<string>();
foreach(var line in textLines)
{
var result = Regex.Replace(line, #"_(.*)\s", match =>
{
return $"~{match.Groups[1].Value.ToUpper()} ";
});
results.Add(result);
}
File.WriteAllLines(#"c:\Users\Darren\Desktop\newHello.txt", results.ToArray());
Instead of return $"~{match.Groups[1].Value.ToUpper()} "; you can place the code that transforms the text in the way you want. match.Groups[1].Value will contain the text after the _ and before the space

Search text file for text above which pattern matches input

I am trying to make my program display the text above the input text which matches a pattern I set.
For example, if user input 'FastModeIdleImmediateCount"=dword:00000000', I should get the closest HKEY above, which is [HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000] for this case.
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]
"StandardModeIdleImmediateCount"=dword:00000000
"FastModeIdleImmediateCount"=dword:00000000
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD\DEVICE0]
"Attach.ToDesktop"=dword:00000001
Could anyone please show me how I can code something like that? I tried playing around with regular expressions to match text with bracket, but I am not sure how to make it to only search for the text above my input.
I'm assuming your file is a .txt file, although it's most probably not. But the logic is the same.
It is not hard at all, a simple for() loop would do the trick.
Code with the needed description:
string[] lines = File.ReadAllLines(#"d:\test.txt");//replace your directory. We're getting all lines from a text file.
string inputToSearchFor = "\"FastModeIdleImmediateCount\"=dword:00000000"; //that's the string to search for
int indexOfMatchingLine = Array.FindIndex(lines, line => line == inputToSearchFor); //getting the index of the line, which equals the matchcode
string nearestHotKey = String.Empty;
for(int i = indexOfMatchingLine; i >=0; i--) //looping for lines above the matched one to find the hotkey
{
if(lines[i].IndexOf("[HKEY_") == 0) //if we find a line which begins with "[HKEY_" (that means it's a hotkey, right?)
{
nearestHotKey = lines[i]; //we get the line into our hotkey string
break; //breaking the loop
}
}
if(nearestHotKey != String.Empty) //we have actually found a hotkey, so our string is not empty
{
//add code...
}
You could try to split the text into lines, find the index of the line that contains your text (whether exact match or regex is used doesn't matter) and then backsearch for the first key. Reverse sorting the lines first might help.

how to find indexof substring in a text file

I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.
I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.
My question is:
What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?
I would say IndexOf() / IndexOfAny() together with Substring(). Alternatively, regular expressions. It the file has an XML-like structure, this.
If the files are delimited eg with commas you can use string.Split
If data is: string[] text = { "1, apple", "2, orange", "3, lemon" };
private void button1_Click(object sender, EventArgs e)
{
string[] lines = this.textBoxIn.Lines;
List<Fruit> fields = new List<Fruit>();
foreach(string s in lines)
{
char[] delim = {','};
string[] fruitData = s.Split(delim);
Fruit f = new Fruit();
int tmpid = 0;
Int32.TryParse(fruitData[0], out tmpid);
f.id = tmpid;
f.name = fruitData[1];
fields.Add(f);
}
this.textBoxOut.Clear();
string text=string.Empty;
foreach(Fruit item in fields)
{
text += item.ToString() + " \n";
}
this.textBoxOut.Text = text;
}
}
The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.
Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?
Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.
You can use indexOf() and then use Length() as the second substring parameter
substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));

Categories