我的文本文件包含以下格式的机场代码:
"AAA","","Anaa Arpt","PF","","","AAA","2","N","272"
我使用StreamReader
来读取文件中的行,然后我将该行添加到字符串列表中,最后将该列表转换为IEnumerable
类型。
你能帮我解决一下,我怎样才能从每一行得到三个值,例如
AAA
是airportCode Anna Arpt
机场名称PF
是国家/地区代码我想从每一行只获得这三个值。
请在下面找到代码。
using (StreamReader sr = new StreamReader("C:/AirCodes/RAPT.TXT"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
aircodesFromTravelPort.Add(line);
Console.WriteLine(line);
}
}
var codes = (IEnumerable<String>)aircodesFromTravelPort;
foreach (var aircode in codes)
答案 0 :(得分:3)
您似乎可以尝试使用 Linq ,类似的东西:
var codes = File
.ReadLines(@"C:/AirCodes/RAPT.TXT")
.Select(line => line.Split(','))
.Select(items => new {
// I've created a simple anonymous class,
// you'd probably want to create you own one
Code = items[0].Trim('"'), //TODO: Check numbers
Airport = items[2].Trim('"'),
Country = items[3].Trim('"')
})
.ToList();
...
foreach(var item in codes)
Console.WriteLine(item);
答案 1 :(得分:2)
您可能希望在每一行上使用String的Split
函数将值放入数组中。
while ((line = sr.ReadLine()) != null)
{
var values = line.Split(","); // here you have an array of strings containing the values between commas
var airportCode = values[0];
var airportName = values[2];
var airportCountry = values[3];
var airportInfo = airportCode + "," + airportName + "," + airportCountry;
aircodesFromTravelPort.Add(airportInfo );
// what you actually do with the values is up to you, I just tried to make it as close to the original as possible.
Console.WriteLine(airportInfo);
}
希望这有帮助!
答案 2 :(得分:0)
我喜欢带有命名群组的Regex
:
var line = @"""AAA"","""",""Anaa Arpt"",""PF"","""","""",""AAA"",""2"",""N"",""272""";
var pattern = @"^""(?<airportCode>\w+)"",""(\w*)"",""(?<ariportName>[\w\s]+)"",""(?<cuntryCode>\w+)""";
Match match = Regex.Match(line, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string airportCode = match.Groups["airportCode"].Value;
string ariportName = match.Groups["ariportName"].Value;
string cuntryCode = match.Groups["cuntryCode"].Value;
}