两个标题的复杂连接

本文关键字:复杂 连接 标题 两个 | 更新日期: 2023-09-27 18:11:24

如果我在。txt文件中有以下标题:

     CUSTOMER             PAYMENT       ERR CORR    PAYMENT AMOUNT     PAYMENT  
  REFERENCE NUMBER    INSTRUCTION TYPE   REASON*                        TYPE**

如何创建包含以下元素的List<string>:

CUSTOMER REFERENCE NUMBER, PAYMENT INSTRUCTION TYPE, ERR CORR REASON*, PAYMENT AMOUNT, PAYMENT TYPE**

另一个例子:

     CUSTOMER             PAYMENT       ERR CORR    PAYMENT AMOUNT     PAYMENT  
  REFERENCE NUMBER    INSTRUCTION TYPE                                  TYPE**

会给我:CUSTOMER REFERENCE NUMBER, PAYMENT INSTRUCTION TYPE, ERR CORR, PAYMENT AMOUNT, PAYMENT TYPE**

注意标题之间用若干空格隔开>= 2,而一个标题中的每个单词之间用一个空格隔开。标题可以只写在第一行

两个标题的复杂连接

有一种方法。首先,将这两行"合并"在一起。我假设它们长度相同。例子:

var s1 = "    CUSTOMER             PAYMENT       ERR CORR    PAYMENT AMOUNT     PAYMENT  ";
var s2 = " REFERENCE NUMBER    INSTRUCTION TYPE   REASON*                        TYPE**  ";
var merged = new string(Enumerable.Range(0, s1.Length)
    .Select(t=>s1[t]!=' ' ? s1[t] : s2[t]).ToArray());

这会得到类似于:

 REFCUSTOMERUMBER    INSTPAYMENT TYPE  ERRACORR    PAYMENT AMOUNT     PAYMENT  

然后,在该字符串中查找双(或更多)空格的索引:

var indexes = Regex.Matches(merged, @"  +").OfType<Match>().Select(t=>t.Index).ToList();

然后,使用这些索引切断两个字符串并将它们连接起来,修剪掉空白。我显式地添加了字符串的开始和结束,以防末尾没有双空格。

indexes.Insert(0, 0);
indexes.Add(merged.Length-1);
indexes.Sort(); // not sure if Regex.Matches will necessarily be in order
var columns = new List<string>();
for (int i=0; i<indexes.Count-1;i++) 
{
    var column = (
        s1.Substring(indexes[i], indexes[i+1]-indexes[i]).Trim() + " " + 
        s2.Substring(indexes[i], indexes[i+1]-indexes[i]).Trim()
        ).Trim();
    if (column != string.Empty) 
        columns.Add(column);
}

输出:

CUSTOMER REFERENCE NUMBER 
PAYMENT INSTRUCTION TYPE 
ERR CORR REASON* 
PAYMENT AMOUNT 
PAYMENT TYPE** 

这里是一个工作示例

如果文本的格式和你说的一样,这里有一个演示

string[] arr = {
                            @" CUSTOMER             PAYMENT       ERR CORR    PAYMENT AMOUNT     PAYMENT  
REFERENCE NUMBER    INSTRUCTION TYPE   REASON*                        TYPE**",
                                                                            @"      CUSTOMER             PAYMENT       ERR CORR    PAYMENT AMOUNT     PAYMENT  
REFERENCE NUMBER    INSTRUCTION TYPE                                  TYPE**"
                        };
foreach (string str in arr)
{
    List<string> list = new List<string>();
    var tmp = Regex.Split(str.Trim(), @"'s{2,}");
    list.Add(tmp[0] + " " + tmp[5]);
    list.Add(tmp[1] + " " + tmp[6]);
    if (tmp.Length == 9)
    {
        list.Add(tmp[2] + " " + tmp[7]);
    }
    else
    {
        list.Add(tmp[2]);
    }
    list.Add(tmp[3]);
    list.Add(tmp[4] + " " + tmp[tmp.Length - 1]);
    Console.WriteLine(string.Join(",", list));
}