简体   繁体   中英

Extract 2 int value inside a string C#?

I have this code:

int[,] matSong;
int nNote = 0;

OpenFileDialog Of = new OpenFileDialog();
Of.ShowDialog();

StreamReader fp = new StreamReader(Of.FileName);
nNote = Convert.ToInt32(fp.ReadLine());

matSong = new int[2, nNote];

int i = 0;
string buffer = fp.ReadLine();

while (buffer != null)
{
    int.TryParse(buffer, out matSong[0, i]);
    int.TryParse(buffer, out matSong[1, i]);
    MessageBox.Show(buffer);
    buffer = fp.ReadLine();
    i++;
}

The strings that I read from file are like this "123 400" or "1234 500" or "1234 1000".

The solution int.Tryparse() doesn't work.

How can I save the 2 numbers into my matrix ?

The file.txt is like this:

4
123 400
234 500
354 700
233 500

if you have another solution to put the numbers into my matrix I would be gratefull.

I'm apologise for my english and I hope you can undestand my problem.

Thankyou vary much for you help.

Matteo Angella

Instead of reading the file line by line you should read it word by word:

string text = System.IO.File.ReadAllText(Of.FileName);
string[] words = text.Split(' ');

You could try it with

string[] words = fp.ReadToEnd().Split(' '); 

But as mentioned in the comments it will not interpret the line breaks correctly.

You can split your strings:

while (buffer != null)
{
    var words = buffer.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
    int.TryParse(words[0], out matSong[0, i]);
    int.TryParse(words[1], out matSong[1, i]);
    buffer = fp.ReadLine();
    i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM