The number of times a word is repeated in the text box - c#

How can I make the program count how often a Pre-selected word is repeated and put it in a new text box called result and this code to colors the chosen word. What should i do now?.
int index = 0;
string temp = richTextBox1.Text;
richTextBox1.Text = "";
richTextBox1.Text = temp;
while (index < richTextBox1.Text.LastIndexOf(word.Text))
{
richTextBox1.Find(word.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Blue;
index = richTextBox1.Text.IndexOf(word.Text, index) + 1;
result.Text = //???

This might help you to set the BackColor of the words and also output the count.
int i = richTextBox1.Text.IndexOf(word.Text);
int count = 1;
while (i > -1)
{
richTextBox1.Select(i, word.Text.Length);
richTextBox1.SelectionBackColor = Color.Blue;
i = richTextBox1.Text.IndexOf(word.Text, i + 1);
result.Text = count++.ToString();
}

Related

Is it possible to write into a RichTextBox at a given line, column?

I have a WinForm with a RichTextBox.
I am trying to write into the RichTextBox at a given line and column:
Here is the code:
public Form1()
{
InitializeComponent();
richTextBox1 = new RichTextBoxWithMouseSelectionFixed();
richTextBox1.Location = new System.Drawing.Point(62, 46);
richTextBox1.Name = "richTextBox1";
richTextBox1.Size = new System.Drawing.Size(461, 391);
richTextBox1.TabIndex = 0;
richTextBox1.Text = "";
richTextBox1.HideSelection = false;
Controls.Add(richTextBox1);
int line = 3;
int column = 5;
GoToLineAndColumn(richTextBox1, line, column);
}
private RichTextBoxWithMouseSelectionFixed richTextBox1;
private void GoToLineAndColumn(RichTextBox richTextBox1, int line, int column)
{
int offset = 0;
for (int i = 0; i < line - 1 && i < richTextBox1.Lines.Length; i++)
{
offset += richTextBox1.Lines[i].Length + 1;
}
richTextBox1.Focus();
richTextBox1.Select(offset + column, 0);
}
I tryed to write with:
richTextBox1.AppendText("currentWord");
and also with:
richTextBox1.Text = "currentWord";
but in both cases the currentWord is written in the first line at column 0.
public Form1()
{
InitializeComponent();
int line = 6;
int column = 30;
RichTextBox richTextBox1 = new RichTextBox();
richTextBox1.Location = new System.Drawing.Point(62, 46);
richTextBox1.Name = "richTextBox1";
richTextBox1.Size = new System.Drawing.Size(461, 391);
richTextBox1.TabIndex = 0;
richTextBox1.Text = "";
richTextBox1.HideSelection = false;
Controls.Add(richTextBox1);
for (int i = 0; i < line - 1; i++)
richTextBox1.Text += "\n";
for (int i = 0; i < column - 1; i++)
richTextBox1.Text += " ";
richTextBox1.Text += "Just Text";
}
The RichTextBox class has properties you can use to write text to a specific index in it. first you define the zero based index of the line and column you would like to write to and then you get the index of the first character in that line like below
// define the index of the line and the column of the line you want to write to in the rich text box
int lineIndex = 2;
// zero-based index of the line
int columnIndex = 10;
// Get the index of the first character in that line you specified above
int index = richTextBox.GetFirstCharIndexFromLine(lineIndex) + columnIndex;
//declare the string you wish to paste
string mytext = "Write to this section only";
//Use the SelectionStart and SelectionLength properties to write the text
richTextBox.SelectionStart = index;
richTextBox.SelectionLength = mytext.Length;
// clear any previous selection
richTextBox.SelectedText = mytext;
The only solution I found is by adding empty lines before the text and blank characters before the text:
private void WriteAtLineAndColumn(RichTextBox richTextBox1, string text, int line, int column)
{
// Insert blank lines at the beginning of the RichTextBox.
for (int i = 0; i < line - 1; i++)
{
richTextBox1.AppendText(Environment.NewLine);
}
int index = richTextBox1.GetFirstCharIndexFromLine(line - 1);
richTextBox1.Select(index, 0);
string spaces = new string(' ', column);
richTextBox1.SelectedText = spaces + "This is a sample text";
// Insert the text at the desired position.
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(line - 1) + column, 0);
richTextBox1.SelectedText = text;
}

How not to reset vertex colors after updating text?

I have a simple coroutine which is printing text by symbol outputing result in TextMeshProUGUI.
IEnumerator TextPrint(TextMeshProUGUI output, string input, float delay, bool skip)
{
for (int i = 1; i <= input.Length; i++)
{
if (skip) { output.text = input; break; }
output.text = input.Substring(0, i);
yield return new WaitForSeconds(delay);
}
toSkip = true;
}
And I have a task to edit colors of individual characters. To do that I prepared a code that is looking for color tag in input text and activating so-called colorMode (just a boolean).
IEnumerator TextPrint(TextMeshProUGUI output, string input, float delay, bool skip)
{
for (int i = 1; i <= input.Length; i++)
{
//looking for color tag like <#A63F3F>
if (i < input.Length - 1 && input.Substring(i, 1) == "<")
{
if (i < input.Length - 2 && input.Substring(i+1, 1) == "#")
{
//writing color to storedColor (string variable)
int k = 0;
storedColor = "";
while (input.Substring(i+2+k, 1) != ">")
{
storedColor += input.Substring(i + 2 + k++, 1);
}
//removing color tag from input (we don't need to print it)
input = input.Remove(i, k + 3);
colorMode = true;
}
}
if (skip) { output.text = input; break; }
typingSound.PlayOneShot(typingClip);
output.text = input.Substring(0, i);
if (colorMode)
{
output.ForceMeshUpdate();
//getting necessary info of the last character and changing its color
var textInfo = output.textInfo;
var charInfo = textInfo.characterInfo[textInfo.characterCount - 1];
int meshIndex = charInfo.materialReferenceIndex;
int vertexIndex = charInfo.vertexIndex;
//hexToRgb is a function converting hex color to Color32, and it's working fine
Color32[] vertexColors = textInfo.meshInfo[meshIndex].colors32;
vertexColors[vertexIndex + 0] = hexToRgd(storedColor);
vertexColors[vertexIndex + 1] = hexToRgd(storedColor);
vertexColors[vertexIndex + 2] = hexToRgd(storedColor);
vertexColors[vertexIndex + 3] = hexToRgd(storedColor);
output.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
}
yield return new WaitForSeconds(delay);
}
toSkip = true;
}
But after printing another character using output.text = input.Substring(0, i); vertex colors are being reset back to white. I spent some time trying to find some info of how to save applied vertex colors but found only a solution when it's necessary to update all colors after every update of text. I find this solution bad for perfomance and trying to find something else. So can somebody give some peace of advice of how to do this task correctly?

How can i use a numericUpDown to move to specific location text in richTextBox?

In the listView selected index i select item and display the file content in richTextBox:
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
{
richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
int resultsnumber = 0;
int start = richTextBox1.SelectionStart;
int startIndex = 0;
int index = 0;
string word = textBox1.Text;
Color selectionColor = richTextBox1.SelectionColor;
word = textBox1.Text.Replace("\r\n", "\n");
while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
{
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Yellow;
startIndex = index + word.Length;
resultsnumber ++;
}
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = selectionColor;
label16.Text = resultsnumber.ToString();
label16.Visible = true;
numericUpDown1.Maximum = resultsnumber;
numericUpDown1.Enabled = true;
}
}
And i have the numericUpDown changedvalue event
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
for example if i have in the numericUpDown the maximum value of 4 that's 4 results in the richTextBox text.
Each result is in another place in the text.
What i want to do is when i move up down with the numericUpDown it will jump in the richTextBox to the result location in the text.
I think it should be that if the first result started in index 0 and ended in index 20 then jump to this result show this result.
If the third result is started in index 76 and ended in index 83 so if i selected in the numericUpDown the value 3 jump to this result location.
Ok this is what i did now it was quite easy but i have a problem reseting the variable:
It was easy to do it but i have a problem reseting the variables when selecting another item each time in the listView. I want to reset the List and also to set the numericUpDown1 to value 0 when selecting other item. But then it's going to the numericUpDown1_ValueChanged item before it's adding items to the List and throw exception since the List Count and the numericUpDown1 value are 0.
In top of form1 created a new List
private List<int> results = new List<int>();
In the listView selectedindex event:
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
{
richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
results = new List<int>();
numericUpDown1.Value = 0;
int resultsnumber = 0;
int start = richTextBox1.SelectionStart;
int startIndex = 0;
int index = 0;
string word = textBox1.Text;
Color selectionColor = richTextBox1.SelectionColor;
word = textBox1.Text.Replace("\r\n", "\n");
while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
{
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Yellow;
startIndex = index + word.Length;
resultsnumber ++;
results.Add(startIndex);
}
richTextBox1.SelectionStart = start;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = selectionColor;
label16.Text = resultsnumber.ToString();
label16.Visible = true;
numericUpDown1.Maximum = results.Count -1;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value];
richTextBox1.ScrollToCaret();
}
}
In the numericupdown1 valuechanged event
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (results.Count == 0)
{
MessageBox.Show("Results Count Value is 0 Check It !!!!!");
}
else
{
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value];
richTextBox1.ScrollToCaret();
}
}
When selecting first item in the listView it's fine.
But then when selecting any other item i want that the results List and the numericUpDown will be reset to empty and 0.
The problem is when i set the numericUpDown1 Value to 0 it's jumping to the valuechanged event before it's adding the results to the List so it's giving the exception.

Highlight all searched words

In my RichtextBox, if I have written as below.
This is my pen,
his pen is beautiful.
Now I search word "is" then
output would be as below.
All "is" should be highlighted.
What about:
static class Utility {
public static void HighlightText(this RichTextBox myRtb, string word, Color color) {
if (word == string.Empty)
return;
int s_start = myRtb.SelectionStart, startIndex = 0, index;
while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) {
myRtb.Select(index, word.Length);
myRtb.SelectionColor = color;
startIndex = index + word.Length;
}
myRtb.SelectionStart = s_start;
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
}
Looks like this would do it.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=146
int start = 0;
int indexOfSearchText = 0;
private void btnFind_Click(object sender, EventArgs e)
{
int startindex = 0;
if(txtSearch.Text.Length > 0)
startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
// If string was found in the RichTextBox, highlight it
if (startindex >= 0)
{
// Set the highlight color as red
rtb.SelectionColor = Color.Red;
// Find the end index. End Index = number of characters in textbox
int endindex = txtSearch.Text.Length;
// Highlight the search string
rtb.Select(startindex, endindex);
// mark the start position after the position of
// last search string
start = startindex + endindex;
}
}
public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
{
// Unselect the previously searched string
if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
{
rtb.Undo();
}
// Set the return value to -1 by default.
int retVal = -1;
// A valid starting index should be specified.
// if indexOfSearchText = -1, the end of search
if (searchStart >= 0 && indexOfSearchText >=0)
{
// A valid ending index
if (searchEnd > searchStart || searchEnd == -1)
{
// Find the position of search string in RichTextBox
indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
// Determine whether the text was found in richTextBox1.
if (indexOfSearchText != -1)
{
// Return the index to the specified search text.
retVal = indexOfSearchText;
}
}
}
return retVal;
}
// Reset the richtextbox when user changes the search string
private void textBox1_TextChanged(object sender, EventArgs e)
{
start = 0;
indexOfSearchText = 0;
}
This will show all the searched criteria at the same time.
Using: 1 Textbox (to enter the text to search for) and 1 Button (to Run the Search).
Enter your search criteria inside the textbox and press search button.
// On Search Button Click: RichTextBox ("rtb") will display all the words inside the document
private void btn_Search_Click(object sender, EventArgs e)
{
try
{
if (rtb.Text != string.Empty)
{// if the ritchtextbox is not empty; highlight the search criteria
int index = 0;
String temp = rtb.Text;
rtb.Text = "";
rtb.Text = temp;
while (index < rtb.Text.LastIndexOf(txt_Search.Text))
{
rtb.Find(txt_Search.Text, index, rtb.TextLength, RichTextBoxFinds.None);
rtb.SelectionBackColor = Color.Yellow;
index = rtb.Text.IndexOf(txt_Search.Text, index) + 1;
rtb.Select();
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); }
}
}
}
If you only want to match the whole word you can use this, note that this ignores case and also the |s\b means that plurals get highlighted e.g. Cat matches cats but not caterpiller :
public static void HighlightText(RichTextBox myRtb, string word, Color color)
{
if (word == string.Empty)
return;
var reg = new Regex(#"\b" + word + #"(\b|s\b)",RegexOptions.IgnoreCase);
foreach (Match match in reg.Matches(myRtb.Text))
{
myRtb.Select(match.Index, match.Length);
myRtb.SelectionColor = color;
}
myRtb.SelectionLength = 0;
myRtb.SelectionColor = Color.Black;
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.Find(textBox1.Text, i, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Red;
}
}
else
{
for (int i = 0; i < richTextBox1.TextLength; i++)
{
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
}
}
}[lets make it!][1]
I would do it like that because all the other answers highlight the text, but doesnt change it back after you searched again.
Use the RichText Find Method to find the starting index for the searching word.
public int FindMyText(string searchText, int searchStart, int searchEnd)
{
int returnValue = -1;
if (searchText.Length > 0 && searchStart >= 0)
{
if (searchEnd > searchStart || searchEnd == -1)
{
int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
if (indexToText >= 0)
{
returnValue = indexToText;
}
}
}
return returnValue;
}
Use a Button or TextChangeListener and Search for your word.
private void button1_Click(object sender, EventArgs e)
{
// Select the first char in your Richtextbox
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = richTextBox1.TextLength;
// Select until the end
richTextBox1.SelectionColor = Color.Black;
// Make the Text Color black
//Use an Inputfield to add the searching word
var word = txtSearch.Text;
//verify the minimum length otherwise it may freeze if you dont have text inside
if (word.Length > 3)
{
int s_start = richTextBox1.SelectionStart, startIndex = 0, index;
while ((index = FindMyText(word, startIndex, richTextBox1.TextLength)) != -1)
{
// goes through all possible found words and color them blue (starting index to end)
richTextBox1.Select(index, word.Length);
richTextBox1.SelectionColor = Color.Blue;
startIndex = index + word.Length;
}
// Color everything between in color black to highlight only found words
richTextBox1.SelectionStart = startIndex;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectionColor = Color.Black;
}
}
I would highly recommend to set a minimum word length to avoid freezing and high memory allocation.

How to continue from where I have been searching to find the index?

How to continue from where I have been searching to find the index?
I am searching in a file to find the index of a character; then I have to continue from there to find the index of the next character. For example : string is " habcdefghij"
int index = message.IndexOf("c");
Label2.Text = index.ToString();
label1.Text = message.Substring(index);
int indexend = message.IndexOf("h");
int indexdiff = indexend - index;
Label3.Text = message.Substring(index,indexdiff);
so it should return "cedef"
but the second search starts from the beginning of the file, it will return the index of first h rather than second h:-(
You can specify a start index when using String.IndexOf.
Try
//...
int indexend = message.IndexOf("h", index);
//...
int index = message.IndexOf("c");
label1.Text = message.Substring(index);
int indexend = message.IndexOf("h", index); //change
int indexdiff = indexend - index;
Label3.Text = message.Substring(index, indexdiff);
This code finds all the matches, and shows them in order:
// Find the full path of our document
System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
string path = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "MyTextFile.txt");
// Read the content of the file
string content = String.Empty;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
}
// Find the pattern "abc"
int index = content.Length - 1;
System.Collections.ArrayList coincidences = new System.Collections.ArrayList();
while(content.Substring(0, index).Contains("abc"))
{
index = content.Substring(0, index).LastIndexOf("abc");
if ((index >= 0) && (index < content.Length - 4))
{
coincidences.Add("Found coincidence in position " + index.ToString() + ": " + content.Substring(index + 3, 2));
}
}
coincidences.Reverse();
foreach (string message in coincidences)
{
Console.WriteLine(message);
}
Console.ReadLine();

Categories