所以问题是:我想从文件中读取并排除某些字符串(我没有经验,所以我决定使用IF,所以我想排除字符串Name,facultyNumber等,但是在某些情况下却不排除它们原因(我试图从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
答案 0 :(得分:2)
您可以像这样使用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);
}
答案 1 :(得分:1)
您应该&&
所有条件。由于||
的偏好是从左到右,因此如果最左边的条件为true,则将不考虑其他条件。因此,如果单词通过条件!words[j].Equals(" Name: ")
的这部分,它将通过整个条件。因此,如果有一个类似FacultyNumber
或Grades
的单词通过了第一个条件,则您将无法获得指定的内容。您可以像下面这样修改代码:
if (!(words[j].Equals(" Name: ") ||
words[j].Equals(" FacultyNumber: ") ||
words[j].Equals(" Grades: ") ||
words[j].Equals(" AverageGrade: ")))
答案 2 :(得分:1)
我对编程还很陌生,不知道使用string.Replace方法是否有任何缺点,但这就是我的做法。
public void read()
{
string[] textes = File.ReadAllLines(@"C:\Users\sashk\Source\Repos\ConsoleApp6\ConsoleApp6\save.txt", Encoding.Default);
List<string> texts = new List<string>();
for (int i = 0; i < textes.Lenght; i++)
{
texts.Add(textes[i].Replace(" Name: ", ""));
texts.Add(textes[i].Replace(" FacultyNumber: ", ""));
texts.Add(textes[i].Replace(" Grades: ", ""));
texts.Add(textes[i].Replace(" AverageGrade: ", ""));
}
foreach (string text in texts)
{
Debug.WriteLine(text);
}
}