所以基本上我有一个文本数据文件,其中包含篮球运动员的姓名和身高,即“ Tom is 6 ft”。从这个带有篮球运动员姓名和身高的文本文件中,我试图编写一个贯穿文本数据文件每一行并从字符串中分离数字的代码,并发现如果一个运动员大于6英尺,则该运动员已将其发送给团队,并将该球员发送到另一个名为“ make it”的文本文件中。知道结果已得到解释,我在尝试创建代码以将数字与字符串分开并识别玩家(如果玩家为6英尺或以上)并将该玩家放入新的文本数据文件时遇到了麻烦。
这是文本数据文件,其中包含程序所需的名称和高度:https://drive.google.com/file/d/10qLuyOzrV2EhFsQ9g4-28rLGIlLFGoDt/view?usp=sharing
现在,我设法创建了一个程序,可以读取文本数据文件并写入另一个文本数据文件,同时还在控制台上逐行显示文本文件中的所有信息。
这是我现在拥有的代码:
using System;
namespace basketball
{
class Program
{
static void Main(string[] args)
{
// This section shows how to read a file called Sample.txt stored in the Debug folder of the program folder
string fileName = @"Sample.TXT";
Console.WriteLine("The contents of the file {0} is:", fileName);
string[] dataFromFile = new string[100];
int index = 0;
System.IO.StreamReader streamReader = new System.IO.StreamReader(fileName);
using (streamReader)
{
string fileContents = streamReader.ReadToEnd();
dataFromFile[index] = fileContents;
Console.WriteLine(dataFromFile[index]);
index++;
}
Console.WriteLine("Now Line By Line:");
System.IO.StreamReader reader = new System.IO.StreamReader(fileName);
using (reader)
{
int lineNumber = 0;
string line = reader.ReadLine();
while (line != null)
{
lineNumber++;
Console.WriteLine("Line {0}: {1}", lineNumber, line);
line = reader.ReadLine();
}
}
// This section shows how to write a file called madeit.txt stored in the console programs debug folder
string fileName2 = @"madeit.txt";
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileName2);
using (streamWriter)
{
for (int number = 1; number <= 20; number++)
{
streamWriter.WriteLine("This is line number : " + number);
}
}
Console.WriteLine("File is written!");
}
}
}
这是当前控制台输出的样子,这里是一个链接:https://drive.google.com/file/d/13_WKzfVriXlnfRcaqaPWbNFkc4Xix5z2/view?usp=sharing
答案 0 :(得分:0)
我建议使用正则表达式。请参见以下示例:
List<string> players = new List<string> {
@"Grady is 6'1"" ft",
@"Robert is 5'10"" ft",
@"Riley is 7 ft",
@"Sam is 4'9"" ft",
@"Greg is 6 ft",
@"Raheem is 6'3"" ft",
@"Connor is 5'11"" ft"
};
const string pattern = @"(.+) is (\d+)('\d+"")? ft";
var regex = new Regex(pattern);
foreach (var player in players)
{
var match = regex.Match(player);
if (match.Success)
{
bool sixFeetOrTaller = false;
var name = match.Groups[1].Value;
var inchesStr = match.Groups[2].Value;
int inches;
if (int.TryParse(inchesStr, out inches))
{
if (inches >= 6)
{
sixFeetOrTaller = true;
}
}
if (sixFeetOrTaller)
{
Console.WriteLine(name + " made it to the team!");
}
else
{
Console.WriteLine(name + " did not make it to the team");
}
}
else
{
Console.WriteLine("Unable to parse line " + player);
}
}
输出:
Grady made it to the team!
Robert did not make it to the team
Riley made it to the team!
Sam did not make it to the team
Greg made it to the team!
Raheem made it to the team!
Connor did not make it to the team