【发布时间】:2011-03-16 12:55:47
【问题描述】:
我有一个文本框,用户可以在其中输入字符串。该字符串将如下所示:
G32:04:20:40
然后用户点击搜索按钮。然后程序必须打开一个文本文件并搜索与他们输入的字符串“最近”的五个字符串,并将它们显示在一个列表框中。
我将尽可能多地定义“最近的字符串”(很可能使用一个非常长的复杂示例)。
文本文件中包含的数据如下所示:
G32:63:58:11 JG01
G32:86:98:30 JG01
G33:50:05:11 JG06
G33:03:84:12 JG05
G34:45:58:11 JG07
G35:45:20:41 JG01
G35:58:20:21 JG03
所以如果用户输入字符串:
G33:89:03:20
五个最接近的结果应显示在列表框中,如下所示:
G33:50:05:11 JG06
G33:03:84:12 JG05
G32:86:98:30 JG01
G32:63:58:11 JG01
G34:45:58:11 JG07
此时我可能应该指出,字符串是坐标,“JG”之后的值表示该坐标处某物的值。
我得到这 5 个的方法是逐个遍历字符串。所以用户输入了“G33”,所以我找到所有开头有 G33 的人——如果没有,那么我找到最接近 G33 的人。然后是“89”,所以如果没有的话,我会找到下一部分是“89”的所有那些,然后最接近 89 更好,依此类推。
我需要知道的是我该怎么做?我已经构建了可视化组件,并且我也有处理类似事情的代码,但是当涉及到这一点时,我真的很难过。正如您现在可能知道的那样,我对 C# 相当陌生,但我正在学习 :)
编辑:搜索代码
private void btnSearch_Click(object sender, EventArgs e)
{
lstResult.Items.Clear();
if (txtSearch.Text == String.Empty)
{
MessageBox.Show("The textbox is empty, there is nothing to search.",
"Textbox empty", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
this.CheckFormatting();
}
}
private long GetIndexForCoord(string coord)
{
// gets out a numerical value for each coordinate to make it easier to compare
Regex m_regex = new Regex("\\d\\d:\\d\\d:\\d\\d:\\d\\d");
string cleaned = m_regex.Match(coord).Value;
cleaned = cleaned.Replace(':', '0');
return Convert.ToInt64(cleaned);
}
private List<string> GetResults(string coord)
{
// gets out the 5 closest coordinates
long index = GetIndexForCoord(coord);
// First find the 5 closest indexes to the one we're looking for
List<long> found = new List<long>();
while (found.Count < 5)
{
long closest = long.MaxValue;
long closestAbs = long.MaxValue;
foreach (long i in m_indexes)
{
if (!found.Contains(i))
{
long absIndex = Math.Abs(index - i);
if (absIndex < closestAbs)
{
closest = i;
closestAbs = absIndex;
}
}
}
if (closest != long.MaxValue)
{
found.Add(closest);
}
}
// Then use those indexes to get the coordinates from the dictionary
List<string> s = new List<string>();
foreach (long i in found)
{
s.Add(m_dic[i]);
}
return s;
}
private void CheckFormatting()
{
StringReader objReader = new StringReader(txtSearch.Text);
bool FlagCheck = true;
if (!Regex.IsMatch(txtSearch.Text,
"G3[0-9]{1}:[0-9]{2}:[0-9]{2}:[0-9]{2}"))
{
FlagCheck = false;
}
if (FlagCheck == true)
{
this.CheckAndPopulate();
}
else
{
MessageBox.Show("Your search coordinates are not formatted correctly.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CheckAndPopulate()
{
StreamReader objReader = new StreamReader("Jumpgate List.JG");
List<String> v = new List<String>();
do
{
v.Add(objReader.ReadLine());
}
while (objReader.Peek() != -1);
objReader.Close();
foreach (string c in v)
{
long index = GetIndexForCoord(c);
m_dic.Add(index, c);
m_indexes.Add(index);
}
List<string> results = GetResults(txtSearch.Text);
foreach (string c in results)
{
lstResult.Items.Add(c);
}
}
【问题讨论】:
标签: c# regex winforms search listbox