[英]Ordering writeline outputs from text file using C# in console
我想知道您是否能幫助我。 本質上,我的程序必須掃描文本文件,然后打印行。 如果可能,打印的每一行也必須按字母順序排列。 我可以通過cmd指向任何文件,而不是自動將其指向特定文件和特定位置。
到目前為止,我一直想以一種基本的形式來完成工作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Program
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
//We Have to pass the file path and packages.txt filename to the StreamReader constructor
StreamReader sr = new StreamReader("D:\\Users\\James\\Desktop\\packages.txt");
//Instruction to read the first line of text
line = sr.ReadLine();
//Further Instruction is to to read until you reach end of file
while (line != null)
{
//Instruction to write the line to console window
Console.WriteLine(line);
//The read the next line
line = sr.ReadLine();
}
//Finally close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
我希望你們能幫助我,我很生銹!
我的想法是將字符串轉換為char數組? 然后使用array.sort方法進行修改和排序。
好了朋友們。 根據您的建議,我進行了一些更改。 我現在正在拋出一個異常,因為我們試圖讓它接受一個參數,以便我們將其指向任何文本文件,而不是特定的文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Program
{
class Program
{
static void Main (params string[] args)
{
string PathToFile = args[1];
string TargetPackages = args[2];
try
{
string[] textLines = File.ReadAllLines(PathToFile);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(TargetPackages))
{
results.Add(line);
}
Console.WriteLine(results);
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
如果只想按第一個單詞排序並輸出,則需要將所有行讀入內存(我希望您的文件不要太大),對行進行排序,然后再將其寫回。
有很多方法可以做到所有這些。 File類具有一些幫助程序功能,這些功能使逐行讀取和寫入文本文件變得非常簡單,而LINQ的OrderBy方法可快速進行排序。
File.WriteAllLines(
outputFileName,
File.ReadLines(inputFileName).OrderBy(line => line));
有關它們如何工作的信息,請參見File.WriteAllLines和File.ReadLines 。
如果要加載每一行,請對第一個單詞進行排序,然后重新輸出該行:
File.WriteAllLines(
outputFileName,
File.ReadLines(inputFileName)
.Select(line =>
{
var splits = line.Split(new [] {' '}};
var firstWord = new string(splits[0].OrderBy(c => c));
var newLine = firstWord + line.Substring(firstWord.Length);
return newLine;
}));
請注意,這一次加載和處理一行,因此您不必將整個文件保存在內存中。
最好一次閱讀所有行,然后分別查看每一行,這樣會更好:
List<string> allLines = System.IO.File.ReadLines(pathToFile).ToList();
allLines = allLines.OrderBy(line => line).ToList(); //this orders alphabetically all your lines
foreach (string line in allLines)
{
Console.WriteLine(line);
}
這將按字母順序打印文件中的所有行。
您還可以使用打開應用程序時收到的args參數對路徑進行參數設置:
CMD> pathToYourExe.exe path1 path2 path3
您可以使用項目的“調試”菜單中的DEBUG參數來對此進行模擬
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.