我有一个数组,其中包含我要选择的某些行,A
和B
:
[0] A1
[1] line I don't want to select
[2] B1
[3] line I don't want to select
[4] A2
[5] line I don't want to select
[6] B2
[7] line I don't want to select
[8] line I don't want to select
[9] line I don't want to select
[10] A3
[11] line I don't want to select
[12] B3
总是有一行包含A
的行和包含B
的行,因此在此示例中,这些行将是[1]
,[5]
,[11]
我想选择包含A
的所有行,然后将它们与包含B
的相应行配对,并创建一个如下所示的新数组:
[1] A1,B1
[2] A2,B2
[3] A3,B3
答案 0 :(得分:1)
试试正则表达式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Select_specific_lines_in_an_array
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
string line = "";
int count = 0;
List<List<string>> testlist = new List<List<string>>();
List<string> templist = new List<string>();
System.IO.StreamReader file = new System.IO.StreamReader(FILENAME);
string pattern = @"^(?'letter'[A-Z]+)(?'number'\d+)$";
while ((line = file.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
Match match = Regex.Match(line, pattern);
if (match.Success)
{
Console.WriteLine("Letter : '{0}', Number : '{1}'", match.Groups["letter"], match.Groups["number"]);
templist.Add(line);
if (templist.Count == 2)
{
testlist.Add(templist);
templist = new List<string>();
}
}
}
count = count + 1;
}
file.Close();
Console.ReadKey();
}
}
}
答案 1 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Select_specific_lines_in_an_array
{
class Program
{
static void Main(string[] args)
{
string line = "";
int count = 0;
List<List<string>> testlist = new List<List<string>>();
List<string> templist = new List<string>();
System.IO.StreamReader file = new System.IO.StreamReader("inputfile.txt");
while ((line = file.ReadLine()) != null)
{
if (line != "line I don't want to select")
{
Console.WriteLine(line);
templist.Add(line);
if (templist.Count == 2)
{
testlist.Add(templist);
templist = new List<string>();
}
}
count = count + 1;
}
file.Close();
Console.ReadKey();
}
}
}
注意这不是完美的代码,它的问题是: -it如果它进入A1 A2则依赖它A1 A1然后程序仍将运行 并且工作但是它不会将A1和B1存储在一起它将存储 A1和A2在一起
但是我认为这应该足以让你有一个起点可以解决。
另外,作为最后一个注释,我使用了包含列表而不是多维数组的列表,因为我们一开始并不知道有多少数据是我们想要的。
编辑 - 示例输入文本
A1
line I don't want to select
B1
line I don't want to select
A2
line I don't want to select
B2
line I don't want to select
line I don't want to select
line I don't want to select
line I don't want to select
A3
line I don't want to select
B3