I'm comparing richTextBox1 and richTextBox2 word by word.
// collect words from ritchtextbox1
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word test to richtextbox2
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox1
test = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word in test to richtextbox1
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox2
can any one help me in code i'm little bit poor in syntax.
im taking reference of mateusz code
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=true
break;
}
else wordNotFound=true;
}
//// here i need the to change particular word back color not entire ritchtextbox
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
im not comparing two text boxes im validating each word which is exist in both side or not. just like spell check taking dictionary as one richtextbox1. spell check [valid word] in richtextbox2. vice versa...
var validWords = new HashSet<string>(new string[] { "a","c","e" });
string[] wordsToCheck = new string[] { "a", "b", "c", "d", "e" };
var result = wordsToCheck.Select(w => new
{
Word = w,
IsValid = validWords.Contains(w)
})
.ToList();
If you are only interested in whether all words are valid or not, you can simple check it by
var isOK = wordsToCheck.All(w => validWords.Contains(w));
PS: Of course, new string[]{}s should be replaced with rtb.Split(....) *
If the words would be in the same order why bother with splitting at all?
If it will be ok, I'd do:
if (richtexbox1.text.equals(richtexbox1.text)){
richTextBox1.BackColor = Color.Green;
} else {
richTextBox1.BackColor = Color.Red;
}
If not, and you want to find if both text boxes contain same word but in different order then:
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=false;
break;
}
else wordNotFound=true;
}
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
is giving error;
Error 1 The best overloaded method match for 'string.Split(string[],
System.StringSplitOptions)' has some invalid
arguments C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 29 WindowsFormsApplication5
Error 2 Argument 1: cannot convert from 'string' to
'string[]' C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 53 WindowsFormsApplication5
You could compare each word in textbox1 with textbox2
for(int i = 0; i < stringarray1.length; i++)
{
for(int j = 0; j < stringarray2.length; j++)
{
if(stringarray1[i] == stringarray2[j])
// we have a match
}
}
Related
I have an array that holds user and passwords in user:pass form, and I like ro remove lines which pass is less than 8 characters or password uses repetitive chars like 111111,22222222222,...
I have tried string.take but it takes lines completely, I need conditional deletion.
public string[] lines;
//open file dialogue to load the user pass file
lines = File.ReadAllLines(openFileDialog1.FileName);
//delete button click event
//the place that I have problem
I have email:pass combination like so:
email1:1234567895121
email2:12345
email4:11111
email5"454545454545
and I would like the output to be like
email1:1234567895121
email5"454545454545
Just loop the characters of every line and see if the current is equal to the previous:
public string[] lines = File.ReadAllLines(openFileDialog1.FileName);
var filteredLines = new List<string>(lines);
foreach(var line in lines)
{
var pair = line.Split(':');
var mail = pair[0];
var pass = pair[1]; // may throw exception on invalid format of your line
for(int i = 1; i < pass.Length; i++)
{
if(pass[i] == pass[i - 1])
{
filteredLines.Remove(line);
break; // will break inner loop and continue on next line
}
}
}
string[] lines =
{
"email1:1234567895121",
"email2:12345",
"email3:22222222222",
"email4:11111",
"email5:454545454545"
};
lines = lines
.Where(s =>
{
string pass = s.Split(new[] { ':' }, 2)[1];
return pass.Length >= 8 && pass.Any(c => c != pass[0]);
})
.ToArray();
foreach (var s in lines)
Console.WriteLine(s);
Output:
email1:1234567895121
email5:454545454545
I have 2 strings. These 2 strings can differ in size. I want to look at these 2 strings finding matching sequences. Once I find a change I want to print that word in Capital and then continue on in my string until I find another change and so on. I'm not sure how I would go about this I tried looking at words as a whole but I'm having issues with that. Basically I will have 2 string something like this string one="This is a new value" and string two= "This This is a new also brand value". I want go though each string from the start and find the matching sequences e.g. "This is" stop at string realise it has changed as string was added change it to upper case and then carry on. Expected output ="THIS this is a new ALSO BRAND value "
Some code I was trying. I don't think this is the right approach.
static void Main(string[] args)
{
string one = "This is a new value";
string two = "This This is a new also brand value";
var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());
Console.WriteLine(string.Join(" ", coll));
Console.ReadKey();
}
Is this what you're looking for? The description isn't fantastic, but judging by the answers this seems to be in the same ballpark, and it uses LINQ for less code and complication.
class Program
{
static void Main(string[] args)
{
string one = "This is text one";
string two = "This is string text two not string one";
var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());
Console.WriteLine(string.Join(" ", coll)); // This is STRING text TWO NOT STRING one
Console.ReadKey();
}
}
You can break this out to a separate method and pass your variables in as parameters.
You can convert string to char array and compare chars one by one. You can use the following code i guess.
string one = "this is string one";
string two = "this is string one or two";
char[] oneChar = one.ToCharArray();
char[] twoChar = two.ToCharArray();
int index = 0;
List<char> Diff = new List<char>();
if (oneChar.Length > twoChar.Length)
{
foreach (char item in twoChar)
{
if (item != oneChar[index])
Diff.Add(item);
index++;
}
for (int i = index; i < oneChar.Length; i++)
{
Diff.Add(oneChar[i]);
}
}
else if (oneChar.Length < twoChar.Length)
{
foreach (char item in oneChar)
{
if (item != twoChar[index])
Diff.Add(twoChar[index]);
index++;
}
for (int i = index; i < twoChar.Length; i++)
{
Diff.Add(twoChar[i]);
}
}
else//equal length
{
foreach (char item in twoChar)
{
if (item != oneChar[index])
Diff.Add(item);
}
}
Console.WriteLine(Diff.ToArray());//" or two"
Is that what you need? (Updated)
var value1 = "This is a new Value";
var value2 = "This is also a new value";
var separators = new[] { " " };
var value1Split = value1.Split(separators, StringSplitOptions.None);
var value2Split = value2.Split(separators, StringSplitOptions.None);
var result = new List<string>();
var i = 0;
var j = 0;
while (i < value1Split.Length && j < value2Split.Length)
{
if (value1Split[i].Equals(value2Split[j], StringComparison.OrdinalIgnoreCase))
{
result.Add(value2Split[j]);
i++;
j++;
}
else
{
result.Add(value2Split[j].ToUpper());
j++;
}
}
Console.WriteLine(string.Join(" ", result));
Console.ReadKey();
Note that if for value1="This is a new Value" and value2="This is also a new value" output should be "This is ALSO a new value" than for value1="This is text one" and value2="This is string text two not string one" output will be "This is STRING text TWO NOT STRING one", not "This is STRING TEXT TWO NOT STRING ONE" as you mentioned before.
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();
Ok so I was reworking the current infrastructure for my AI and I created it into an array. But i'm not sure how to get the 11th value to be recognized in the array "dictonary"
Here is the code!
string name = "Jarvis";
string[] dictionary = new string[] { "hello", "how", "are", "you", "sup", "wake", "up", "daddys", "home", "what", "version", "whats", "your" };
bool helloflag = false;
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string code = "";
//ResultText = "Hello how are you"
string[] words = e.Result.Text.Split(' ');
//words = ["Hello", "how", "are", "you"]
foreach (string word in words)
{
for (int index = 0; index < dictionary.Count(); index++)
{
if (word == dictionary[index])
{
code += index.ToString();
}
}
}
//code = "123"; //how are you
//code = "236"; //are you up
//HELLO
if ((code == "0") || (code == "4"))
{
Jarvis.Speak("Hello sir");
helloflag = true;
} else if ((helloflag == true ) && (code == "123"))
{
Jarvis.Speak("im good sir");
helloflag = false;
}
This is part of the .NET speech API, but is using an array to call the words you say.
When you're adding to code, you need to put a separator between the codes. Otherwise, you can't tell whether 12 is word 1 followed by word 2, or word 12. E.g.
code += index.toString() + " ";
Then you can do things like:
if (code == "10 9 2 3 ") // whats version are you
Don't forget the space at the end.
Prob it is more flexible to store your code values in array, e.g.:
var code = new List<int>();
....
code.Add(index);
...
if(code.SequenceEqual(new int[] {1, 2, 3})
{
...
I have this code :
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = textBox1.Text.Split(new char[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
else
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(words[i]);
scrmbltb.GetText();
sb.Append(scrmbltb.scrambledWord);
}
}
textBox2.AppendText(sb.ToString());
}
For example in textBox1 i did typed pressed the space bar key 7 times and then typed some words and then 5 spaces again and a word:
danny hi hello daniel hello
So lets say danny is after 7 spaces from the beginning in textBox1 and between daniel and hello there are more 5 spaces.
In my code i did:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
But that never will happen and its not right.
I wanted to check that if before or after a word in the textBox there is any space/s add the space/s to the sb variable.
So in the end textBox2 content will be the same as in textBox1 with the same number of spaces between the words.
Now textBox2 looks like a long one string of words without any spaces between them.
My problem is how to add the same spaces between the words from textBox1 ?
I simplified your code a little, but you should find it easy to apply in your situation. The problem comes from the fact that you are losing the spaces when you do the split and they are not being added back in. The solution is to use "String.Join" when you have the finished collection of strings. In this case since you know the output size is the same as the input size, I don't see any reason to use the stringbuilder. Just use an array you size to the input.
string inputText = "This is a test";
var words = inputText.Split(new char[] { ' ' });
var outputWords = new string[words.Length];
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
outputWords[i] = words[i];
}
else
{
outputWords[i] = Scramble(words[i]);
}
}
string outputText = string.Join(" ",outputWords);
This statement is absolutely useless:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
It seems you need something like this (not tested):
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)");
foreach (string word in words)
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(word.Trim());
scrmbltb.GetText();
sb.Append(word.Replace(word.Trim(), scrmbltb.scrambledWord));
}
textBox2.AppendText(sb.ToString());
}
Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)") splits the input string with preserving spaces.
This the easy form
string text=mytextbox.Text;
while(text.Contains(" ")) //while two spaces
text=text.Replace(" "," "); //remove two spaces
If i got it right, your problem is to keep the exact number of spaces between the then scrambled words.
var words = string.Split(new char[]{' '}, StringSplitOptions.None); // this keeps the spaces as "epmty words"
var scrambled = words.Select(w => { if (String.IsNullOrEmpty(w))
return w;
else {
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(w);
scrmbltb.GetText();
return scrmbltb.scrambledWord;
}
});
var result = string.Join(" ", scrambled);