【发布时间】:2016-06-10 11:25:36
【问题描述】:
我想知道你是否可以帮助我。本质上,我的程序必须扫描一个文本文件,然后打印这些行。如果可能,打印的每一行也必须按字母顺序排列。我可以通过 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.");
}
}
}
}
【问题讨论】:
-
您的意思是“按字母顺序排列”一行中的每个字符都按字母顺序排序吗?
-
感谢您指出这一点。我的意思是实际上每一行都由一个双空格分隔。每个句子的结构是 word -> word 。所以我基本上需要确保第一个单词是按字母顺序排序的。
-
是否也需要以同样的方式输出? : "dorw -> 单词"
-
我想最好举个例子。假设有三行首先是 dog -> word 第二行 cat -> word 第三行 Mouse -> word 输出应该是三行,但按字母顺序排列(按第一个单词,即 cat 然后 dog 然后 mouse
-
好的,在我编辑了我的帖子后得到了这些新信息。可能这次更适合您的问题。
标签: c# arrays string console.writeline