I am making a syntax coloring tool. I am currently writing the method to find and highlight the keywords, ex if then else.. I am sure there is a better (faster and more aesthetic) way to do this.
Below are two methods, the first I try and not to use any string methods except for length to try and improve speed.
The second I used string methods but I’ve been told they are slower then doing it the first way.
Which way is faster? And for the first one, the word is only highlighted when a space is after that word which is not right, any remedy for that too?
Code:
private string[] m_keywords = new string[] { "GOTO", "IF", "THEN", "ELSE", "WHILE", "DO" };
private int m_nShortestKeywordLength = 2;
// lcpy_strLine is a copy in all uppercase of the current line I am processing
private void ProcessKeywords(Color clr)
{
if(lcpy_strLine.Length > m_nShortestKeywordLength)
for (int i = 0; i < m_keywords.Length; i++)
{
string curWord = m_keywords[i];
int len = curWord.Length;
for (int j = 0; j < lcpy_strLine.Length; j++)
{
if (j + len < lcpy_strLine.Length)
{
int k = 0;
while (k < len && lcpy_strLine[j + k] == curWord[k])
k++;
if (k == len)
{
Console.WriteLine("Found Keyword");
SelectionStart = m_nLineStart + j;
SelectionLength = k;
SelectionColor = clr;
}
}
}
}
}
private void ProcessKeywords2(Color clr)
{
/*for (int i = 0; i < m_keywords.Length; i++)
if (lcpy_strLine.Contains(m_keywords[i]))
{
int indx1 = lcpy_strLine.IndexOf(m_keywords[i]);
SelectionStart = m_nLineStart + indx1;
SelectionLength = m_keywords[i].Length;
SelectionColor = clr;
}*/
}
The easiest way to do this would probably be a regular expression. It’ll be reasonably fast, too.
And no need to uppercase the line: