我需要您的帮助!
因此,我有一个.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ãoPedro Almeida + Rua daAliança,N55%joaoalmeida.pedro @ hotmail.com&915435654!17/11/1997 <987654328>”行,应将字符串相应地分隔到以下文本框:< / p>
字段的分隔符为:“ |”,“ +”,“%”,“&”,“!”,“ <”,“>”>。 我的代码是:
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;
}
}
}
感谢您的帮助,谢谢! 诗:对不起,我的英语...
答案 0 :(得分:3)
获取'text'
行所有部分的最简单方法是使用'String.Split
'方法。
像这样使用它:
foreach (string textLine in text)
{
string[] parts = textLine.Split(new char[] {'|', '+', '%', '&', '!', '<', '>' });
// Now you have all the parts of the line in the `'parts'` `String Array`.
// They can be accessed by index.
}