簡體   English   中英

是否有用於水平字符串連接的內置函數?

[英]Is there a built-in function for horizontal string concatenation?

給定兩個文件:

文件1

aa
bbb
抄送

文件2

dd
ee

Bash有一個命令將水平連接這些文件:

paste File1 File2

阿阿德
bbbee
抄送

C#是否具有行為像這樣的內置函數?

public void ConcatStreams(TextReader left, TextReader right, TextWriter output, string separator = " ")
{
    while (true)
    {
        string leftLine = left.ReadLine();
        string rightLine = right.ReadLine();
        if (leftLine == null && rightLine == null)
            return;

        output.Write((leftLine ?? ""));
        output.Write(separator);
        output.WriteLine((rightLine ?? ""));
    }
}

使用示例:

StringReader a = new StringReader(@"a a a
b b b
c c c";
StringReader b = new StringReader(@"d d
e e";

StringWriter c = new StringWriter();
ConcatStreams(a, b, c);
Console.WriteLine(c.ToString());
// a a a d d
// b b b e e
// c c c 

不幸的是, Zip()想與平等長度的文件,所以Linq中,你必須實現類似的東西的情況下:

public static EnumerableExtensions {
  public static IEnumerable<TResult> Merge<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> map) {

      if (null == first)
        throw new ArgumentNullException("first");
      else if (null == second)
        throw new ArgumentNullException("second");
      else if (null == map)
        throw new ArgumentNullException("map");

      using (var enFirst = first.GetEnumerator()) {
        using (var enSecond = second.GetEnumerator()) {
          while (enFirst.MoveNext())
            if (enSecond.MoveNext())
              yield return map(enFirst.Current, enSecond.Current);
            else
              yield return map(enFirst.Current, default(TSecond));

          while (enSecond.MoveNext())
            yield return map(default(TFirst), enSecond.Current);
        }
      }
    }
  }
}

具有Merge擴展方法,您可以將

var result = File
  .ReadLines(@"C:\First.txt")
  .Merge(File.ReadLines(@"C:\Second.txt"), 
         (line1, line2) => line1 + " " + line2);

File.WriteAllLines(@"C:\CombinedFile.txt", result);

// To test 
Console.Write(String.Join(Environment.NewLine, result));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM