-1

I am trying to extract only numbers from a text file in c#. My text file is like as below

xasd 50 ysd 20 zaf 40 bhar 60

I am trying to browse a file with openfileDialoug and read that file and extract the numbers from the same file and need to compare those values with a constant value say 60. I need to display how many numbers are present more than that constant number. If those numbers are greater than 60 then i need to append the number of greater values to richtextBox along with the existing text.

John Saunders
  • 160,644
  • 26
  • 247
  • 397

3 Answers3

1

You can use the Int32.TryParse(string s,out int result) method. It returns true if the string s can be parsed as an integer and stores the value in int result. Also, you can use the String.Split(Char[]) method to split the line you read from Text File.

 string line = fileObject.ReadLine();
 int constant = 60; //For your example
 int num = 0;
 string []tokens = line.Split(); //No arguments in this method means space is used as the delimeter
 foreach(string s in tokens)
 {
     if(Int32.TryParse(s, out num)
     {
         if(num > constant)
         {
             //Logic to append to Rich Text Box
         }
     }
 }
1

Regex is an elegant way to find numbers in a string which is the OP requirement, something like:

string allDetails = File.ReadAllText(Path);

result = Regex.Match(allDetails, @"\d+").Value;

Now the resultString will contain all the extracted integers

In case you want to take care of negative numbers too=, then do this modification

result = Regex.Match(allDetails, @"-?\d+").Value;

Hope this helps, check out the following post:

Find and extract a number from a string

Community
  • 1
  • 1
Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
0

If your file is always like as you have shown then you can easily split it and parse:

string filePath = ""; // from OpenFileDialog

string fileContents = File.ReadAllText(filePath);
string[] values = fileContents.Split();
int valueInt, greaterValuesCount = 0;    

foreach (var value in values)
{
    if (int.TryParse(value, out valueInt))
    { 
        greaterValueCount++;
        // Do something else here
    }
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101