【发布时间】:2018-10-30 20:45:39
【问题描述】:
我需要你的帮助!
所以,我有一个 .txt 文件,其中包含不同用户的信息,我想将每个用户的不同字段分隔到各自的文本框中。
我的.txt 文件的行是这样的:
1|João Pedro Almeida+Rua da Aliança,N55%joaoalmeida.pedro@hotmail.com&915435654!17/11/1997<987654328>
13|Pedro Costa Rica+Rua de Barcelos ,N47%pedrorica.barcelos@gmail.com&915632154!19/07/1987<237345828>
21|Henrique da Silva+Avenida dos Aliados,N9,Esquerdo%jairofonseca@hotmail.com&963215654!07/01/1993<3453245324>
子字符串永远不会与我想要的方式分开。 例如,对于“1|João Pedro Almeida+Rua da Aliança,N55%joaoalmeida.pedro@hotmail.com&915435654!17/11/1997”这一行,字符串应根据以下文本框进行分隔:
- textBoxId => "1";
- textBoxNome => "若昂·佩德罗·阿尔梅达";
- textBoxMorada => "Rua da Aliança,N55";
- textBoxEmail => "joaoalmeida.pedro@hotmail.com";
- textBoxContacto => "915435654";
- textBoxNasc => "17/11/1997";
- textBoxContr => "987654328";
字段的分隔符有:“|”、“+”、“%”、“&”、“!”、“”。 我的代码是:
private void button1_Click(object sender, EventArgs e)
{
string[] text = File.ReadAllLines(Environment.CurrentDirectory + "/Bd/clientes.txt");
string item;
int indexId;
int indexNome;
int indexMorada;
int indexEmail;
int indexContacto;
int indexNasc;
int indexContr;
foreach (string textLine in text)
{
indexId = textLine.IndexOf('|');
indexNome = textLine.IndexOf('+');
indexMorada = textLine.IndexOf('%');
indexEmail = textLine.IndexOf('&');
indexContacto = textLine.IndexOf('!');
indexNasc = textLine.IndexOf('<');
indexContr = textLine.IndexOf('>');
indexNome -= indexId;
indexMorada -= indexNome;
indexEmail -= indexMorada;
if (indexId > 0)
{
item = textLine.Substring(0, indexId);
textBoxId.Text = item;
}
if (indexNome > 0)
{
indexId = textLine.IndexOf('|');
item = textLine.Substring(indexId + 1, indexNome - 1);
textBoxNome.Text = item;
}
if (indexMorada > 0)
{
indexNome = textLine.IndexOf('+');
indexMorada -= (indexId);
item = textLine.Substring(indexNome + 1, indexMorada - 1);
textBoxMorada.Text = item;
}
if (indexEmail > 0)
{
indexMorada = textLine.IndexOf('%');
indexEmail -= (indexNome + indexId);
item = textLine.Substring(indexMorada + 1, indexEmail + 1);
textBoxEmail.Text = item;
}
if (indexContacto > 0)
{
indexEmail = textLine.IndexOf('&');
indexContacto -= (indexNome + indexId + indexMorada);
item = textLine.Substring(indexEmail + 1, indexContacto + 1);
textBoxContacto.Text = item;
}
if (indexNasc > 0)
{
indexContacto = textLine.IndexOf('!');
indexNasc -= (indexNome + indexId + indexMorada + indexEmail);
//item = textLine.Substring(indexContacto + 1, indexNasc + 1);
//textBoxNasc.Text = item;
}
if (indexContr > 0)
{
indexNasc = textLine.IndexOf('<');
indexContr -= (indexNome + indexId + indexMorada + indexContacto + indexEmail);
//item = textLine.Substring(indexNasc + 1, indexContr);
//textBoxContribuinte.Text = item;
}
}
}
感谢您的帮助,谢谢! Ps.:对不起我的英语......
【问题讨论】:
-
这将是Regular Expressions 的绝佳候选者。
-
“但我在一些文本框中不断收到一些错误的字符”。请详细说明,以便我们了解问题
-
使用 VS 调试器简单地单步调试代码并观察会发生什么
标签: c#