我正在尝试从文件中读取行,但我想排除包含不相关字符的行。我只想打印包含字母字符的行。此外,一旦打印了一行,我就不想再次打印它。这是我当前的代码:
`string[] lines = System.IO.File.ReadAllLines(@"File Location"); //Create line array..
Random rnd1 = new Random(); //Random value
Console.ReadKey();
Console.WriteLine("Contents of file.txt:");
foreach (string line in lines)
{
Console.WriteLine(lines[rnd1.Next(lines.Length)]); //Print random line
}
`
一种方法是在您从文件中读取行时过滤这些行。我们可以通过将每一行视为字符数组来做到这一点,通过将可接受的非字母数字字符作为 an 传递IEnumerable
给Linq
扩展方法来排除可接受的非字母数字字符.Except()
,然后我们可以.All
通过调用结构体的IsLetter
方法来测试其余字符是否为字母char
(如果字符是字母则返回真)。
例如:
Random random = new Random();
static void Main()
{
// Valid non-alphanumeric characters are stored in this list.
// Currently this is only a space, but you can add other valid
// punctuation here (periods, commas, etc.) if necessary.
var validNonAlphaChars = new List<char> {' '};
// Get all lines that contain only letters (after
// excluding the valid non-alpha characters).
var fileLines = File.ReadAllLines(@"c:\temp\temp.txt")
.Where(line => line.Except(validNonAlphaChars).All(char.IsLetter))
.ToList();
// Shuffle the lines so they're in a random order using the Fisher-Yates
// algorithm (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
for (int i = 0; i < fileLines.Count; i++)
{
// Select a random index after i
var rndIndex = i + random.Next(fileLines.Count - i);
// Swap the item at that index with the item at i
var temp = fileLines[rndIndex];
fileLines[rndIndex] = fileLines[i];
fileLines[i] = temp;
}
// Now we can output the lines sequentially from fileLines
// and the order will be random (and non-repeating)
fileLines.ForEach(Console.WriteLine);
GetKeyFromUser("\nPress any key to exit...");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句