Open text file, loop through contents and check against

后端 未结 5 2238
清酒与你
清酒与你 2020-12-21 17:24

So I have a generic number check that I am trying to implement:

    public static bool isNumberValid(string Number)
    {
    }

And I want to

5条回答
  •  失恋的感觉
    2020-12-21 17:42

    First, load all lines of the input file in a string array,
    then open the output file and loop over the array of strings,

    Split each line at the space separator and pass every part to your static method.

    The static method use Int32.TryParse to determine if you have a valid integer or not without throwing an exception if the input text is not a valid Int32 number.

    Based on the result of the method write to the output file the desidered text.

    // Read all lines in memory (Could be optimized, but for this example let's go with a small file)
    string[] lines = File.ReadAllLines(file);
    // Open the output file
    using (StringWriter writer = new StringWriter(outputFile))
    {
        // Loop on every line loaded from the input file
        // Example "1234 ABCD 456 ZZZZ 98989"
        foreach (string line in lines)
        {
            // Split the current line in the wannabe numbers
            string[] numParts = line.Split(' ');
    
            // Loop on every part and pass to the validation
            foreach(string number in numParts)
            {
                // Write the result to the output file
                if(isNumberValid(number))
                   writer.WriteLine(number + " True");
                else
                   writer.WriteLine(number + " False");
            }
        }
    }
    
    // Receives a string and test if it is a Int32 number
    public static bool isNumberValid(string Number)
    {
        int result;
        return Int32.TryParse(Number, out result);
    }
    

    Of course this works only if your definition of 'number' is equal to the allowed values for a Int32 datatype

提交回复
热议问题