【发布时间】:2017-07-20 19:41:01
【问题描述】:
我需要在一些数据中进行搜索。首先,我的代码选择第 29 位并保留 4 位(如您所见,下面是 1721),并比较下面的行。我设法搜索了第 29 个 4 位数字并显示消息,您可以查看行中是否有搜索到的数字,这很容易。这是我的问题;当我搜索号码时,如何让它在标签(label9、label10、label11、label12)上显示前 4 位、第二 3 位、第三 6 位、第四 6 位。我尝试currentLine.Substring(1, 4);但显示错误:
子字符串为空。
我需要在 //search if part 中使用循环吗?
例如,假设我们将 1723 放在搜索上,它必须在 label9 上显示 1097,在 label10 上必须显示 003,等等。
数据:
1096:001:161207:085050:1721:001:F:000:0007
1096:001:161207:085050:1721:001:F:000:0007
1099:003:161207:085719:1722:001:F:000:0007
1099:003:161207:085719:1722:001:F:000:0007
1097:002:161207:085719:1723:001:F:000:0007
1097:002:161207:085719:1723:001:F:000:0007
代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String currentItemIndex = "", currentItemData = "", currentLine = "";
Hashtable hashtable = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
//Select File
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
//Select File
//Read And Split
FileInfo file = new FileInfo(openFileDialog1.FileName.ToString());
StreamReader read = file.OpenText();
currentLine = read.ReadLine();
currentItemIndex = currentLine.Substring(23, 4);
currentItemData += currentLine;
do
{
currentLine = read.ReadLine();
if (currentLine == null)
{
hashtable.Add(currentItemIndex, currentItemData);
break;
}
if (!currentItemIndex.Equals(currentLine.Substring(23, 4)))
{
hashtable.Add(currentItemIndex, currentItemData);
currentItemData = "";
currentItemIndex = currentLine.Substring(23, 4);
}
currentItemData += currentLine;
} while (true);
}
private void button2_Click(object sender, EventArgs e)
{
//Search Start
string search = textBox2.Text;
if (hashtable.ContainsKey(search))
{
MessageBox.Show("Found");
label9.Text=
label10.Text=
label11.Text=
}
else
{
MessageBox.Show("NotFound"); }
//Search End
}
}
}
【问题讨论】:
-
除此之外,您有什么理由使用
Hashtable而不是Dictionary<,>?自 2005 年以来,非泛型集合对于新代码已经有些过时了...... -
您最好将字符串拆分为基于
:的值数组。 -
其实我不知道怎么用
Dictionary -
如果他有大量数据,他可能需要哈希表,字典有点慢,你还必须确保所有字典键在你的数据中都是唯一的。但他可能会考虑在这里查看字典一个入门链接:dotnetperls.com/dictionary