所以问题是:我想从文件中读取并排除某些字符串(我没有经验,所以我决定使用 IF,所以我想排除字符串 Name、failureNumber 等,但它并不排除某些字符串)原因?(我尝试删除 if 语句中的空格)
public void read()
{
string[] textes = File.ReadAllLines(@"C:\Users\sashk\Source\Repos\ConsoleApp6\ConsoleApp6\save.txt", Encoding.Default);
double[] gread = new double[] { 1, 2, 3 };
List<string> texts = new List<string>();
int i= 0;
int z = 0;
foreach (string text in textes)
{
string[] words = textes[i].Split(' ');
for (int j = 0; j < words.Length; j++)
{
if (!words[j].Equals(" Name: ") || !words[j].Equals(" FacultyNumber: ") || !words[j].Equals(" Grades: ") || !words[j].Equals(" AverageGrade: "))
{
texts.Add(words[j]);
}
}
// for (int j = 2; j < texts.Count; j++)
// {
// gread[z] = Convert.ToDouble(texts[j]);
// }
// addStudent(texts[0], Convert.ToInt32(texts[1]), gread);
for (int j = 0; j < 40; j++)
{
Console.WriteLine(texts[j]);
}
i++;
}
文件内容是这样的:
> Name: asd FacultyNumber: 2 Grades: 1,23 4,56 7,89 AverageGrade: 4,56
Name: as FacultyNumber: 4 Grades: 1 5 9 AverageGrade: 5
Name: ad FacultyNumber: 3 Grades: 2 4 7 AverageGrade: 4,33333333333333
Name: ddd00 FacultyNumber: 1 Grades: 12 15 99 AverageGrade: 42
最佳答案
您可以像这样使用Contains
:
var excluded = new[] { "Name:", "FacultyNumber:", "Grades:", "AverageGrade:" };
foreach (string text in textes)
{
string[] words = textes[i].Split(' ');
for (int j = 0; j < words.Length; j++)
{
if (!excluded.Contains(words[j]))
{
texts.Add(words[j]);
}
}
}
但我认为你可以使用 LINQ 来做到这一点。代码会更加简洁:
string[] textes = File.ReadAllLines(@"C:\Users\sashk\Source\Repos\ConsoleApp6\ConsoleApp6\save.txt", Encoding.Default);
var excluded = new[] { "Name:", "FacultyNumber:", "Grades:", "AverageGrade:" };
var texts = textes.SelectMany(x => x.Split(' ').Where(y => !excluded.Contains(y)));
foreach(string word in texts)
{
Console.WriteLine(word);
}
关于C# IF 语句不排除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436324/