if (!text.Contains(pattern)) return;
但是,实际上我正在遍历整个字符串,并将其部分与模式进行比较,所以问题是,String.Contains()
如何工作?我知道有这样一个问题 - How does String.Contains work? 但是答案不太清楚。因此,如果String.Contains()
也遍历整个字符数组并将它们与我要查找的模式进行比较,那么它实际上不会使我的函数更快,而是会变得更慢。
那么,尝试这样的优化是否是一个好主意呢?而且,String.Contains()
是否可能比只遍历整个数组并将每个字符与某个常量字符进行比较的函数更快呢?
以下是代码:
public static char colorchar = (char)3;
public static Client.RichTBox.ContentText color(string text, Client.RichTBox SBAB)
{
if (text.Contains(colorchar.ToString()))
{
int color = 0;
bool closed = false;
int position = 0;
while (text.Length > position)
{
if (text[position] == colorchar)
{
if (closed)
{
text = text.Substring(position, text.Length - position);
Client.RichTBox.ContentText Link = new Client.RichTBox.ContentText(ProtocolIrc.decode_text(text), SBAB, Configuration.CurrentSkin.mrcl[color]);
return Link;
}
if (!closed)
{
if (!int.TryParse(text[position + 1].ToString() + text[position + 2].ToString(), out color))
{
if (!int.TryParse(text[position + 1].ToString(), out color))
{
color = 0;
}
}
if (color > 9)
{
text = text.Remove(position, 3);
}
else
{
text = text.Remove(position, 2);
}
closed = true;
if (color < 16)
{
text = text.Substring(position);
break;
}
}
}
position++;
}
}
return null;
}
position = text.IndexOf(colorchar);
然后position = text.IndexOf(colorchar, position);
。 - Andrei Zubov