简体   繁体   中英

Compare numbers and remove numbers from a text file using C#

I have created a text file with some random float numbers ranging from 743.6 to 1500.4. I am figuring out a way to read the text file (which i have did) and include a number range: lets say( 743.6 <= x <= 800) and remove the numbers which are outside the range and eventually store the final values in a text file.

I have managed to write some codes to read the text file so that when i compile it shows the numbers in the text file. Now i do not know how to progress further . Here is my code, which is able to run compile. This code now ables to read the textfile.

743.6

742.8

744.7

743.2

1000

1768.6

1750

1767

1780

1500

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ReadTextFile
{
    class Program
    {
        static void Main(string[] args)
        {
           string filePath = "C:\\Users\\Student\\Desktop\\ConsoleApp1\\ConsoleApp1\\Data\\TextFile.txt"; // File Direcotry

             List<string> lines = File.ReadAllLines(filePath).ToList();

             foreach (string line in lines)
             {
                 Console.WriteLine(line);
             }
             Console.ReadLine();
        }
    }
}

You need to read all the lines and replace all values between your min and max value with an empty string:

float min = 800.5F, max = 850.5F;
float currentValue;

var lines = File.ReadAllLines(usersPath);
var separator = ';'; // Change this according to which separator you're using between your values (if any)

foreach (var line in lines)
{
    foreach (string word in line.Trim().Split(separator))
    {
        if (float.TryParse(word.Trim(), out currentValue))
        {
            if (currentValue < min || currentValue > max)
            {
                line.Replace(word, "");
            }
        }
    }
}
File.WriteAllLines(usersPath, lines);

This will read the file into memory, parse it, filter it and than overwrite the existing file with the new data.

File.WriteAllLines(filePath,
    File.ReadAllLines(filePath)
      .Select(x => double.Parse(x))
      .Where(x => x >= 800.5 && x <= 850.5)
      .Select(x => x.ToString()));

Here's my solution w/ basic error detection and some robustness thanks to the use of regular expressions. As a foreword: Using regular expressions can be quite expensive and they are not always the way to go.

In this case I think they're okay, because you're handling user-generated input (possibly). Regular expressions can be optimised by pre-compiling them!

/*
    using System;
    using System.IO;
    using System.Text.RegularExpressions;
*/


void ReadFile(string filePath) {
    var fileInfo = default(FileInfo);
    var separator = @"[;\s:,]"; // This is a simple RegEx, can be done otherwise. This allows for a little more robustness IMO

    // VERY rudimentary error detection
    if (string.IsNullOrEmpty(filePath))
        throw new ArgumentNullException(nameof(filePath), "The path to the file must not be null or empty!");

    try {
        fileInfo = new FileInfo(filePath);
    } catch {
        throw new ArgumentException(nameof(filePath), "A valid path must be given!");
    }

    if (!fileInfo.Exists) {
        throw new IOException(string.Format("The file {0} does not exist!", filePath));
    }
    // END VERY rudimentary error checking

    var numberStrings = Regex.Split(File.ReadAllText(fileInfo.FullName), separator);
    // numberStrings is now an array of strings

    foreach (var numString in numberStrings) {
        if (decimal.TryParse(numString, out var myDecimal)) {
            // Do something w/ number
        } else {
            Debug.WriteLine("{0} is NaN!", numString);
        }
    }

}

Here's what the code does (written off the top of my head, please don't just C&P it. Test it first):

At first we're defining the regular expression. This matches any character in the range (between the brackets).

Then we're performing very basic error checking:

  • If the argument passed is null or empty throw an exception
  • If we couldn't parse the argument to a FileInfo object, the path is likely invalid. Throw an exception.
  • If the file doesn't exist, throw an exception.

Next we're reading the entire text file in to memory (not on a per-line basis!) and using the regular expression we've defined to split the entire string in to an array of strings.

At last we're looping through our array of strings and parsing each number to a float (that's what you wanted. I personally would use a double or decimal for more precision. See this video from Tom Scott.).

If the string doesn't parse to a float, then you can handle the error accordingly. Otherwise do what you need to with the variable myFloat.


EDIT: I thought I read you wanting to use floats. My mistake; I changed the datatype to decimal.

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