I have some keywords
private static readonly string[] Keywords =
{
"SELECT", "FROM", "WHERE", "GROUP", "HAVING", "ORDER", "LEFT", "RIGHT", JOIN", "INNER", "OUTER", "ASC", "DESC", "AND", "OR","IN", "BETWEEN", "BY", "NOT", "ON", "AS", "CASE", "WHEN", "ELSE"
};
I want to uppercase these keywords in a string
string Query = "Select * fRom TableA"
This string should be converted to SELECT * FROM TableA
That is, Case will be ignored and keywords will be uppercased.
For this, I have written a function
public static string GetUppercaseKeyword(string sqlStr)
{
string sqlText = string.Empty;
int foundAt = 0;
foreach (var keyword in Keywords)
{
if (sqlStr.IndexOf(keyword, foundAt, StringComparison.CurrentCultureIgnoreCase) == -1)
{
continue;
}
sqlStr = Replace(sqlStr, keyword, keyword.ToUpper(), StringComparison.OrdinalIgnoreCase);
}
return sqlStr;
}
and the replace function is
public static string Replace(string str, string old, string @new, StringComparison comparison)
{
@new = @new ?? "";
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(old))
return str;
int foundAt = 0;
while ((foundAt = str.IndexOf(old, foundAt, StringComparison.CurrentCultureIgnoreCase)) != -1)
{
str = str.Remove(foundAt, old.Length).Insert(foundAt, @new);
foundAt += @new.Length;
}
return str;
}
The thing that happens here is, if a substring matches with the keywords, the method uppercase the substrings, as in Replace method I use IndexOf
For example, select * From OrderTable will output SELECT * FROM ORDERTable.
How can I solve the problem?
My other questions are, is there any easy way to implement it? Is there any existing algorithm for this type of purposes?