简体   繁体   中英

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

Given two files:

File1

aaa
bbb
ccc

File2

dd
ee

Bash has a command that will horizontally concatenate these files:

paste File1 File2

aaadd
bbbee
ccc

Does C# have a built-in function that behaves like this?

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 ?? ""));
    }
}

Example use:

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 

Unfortunately, Zip() wants files with equals lengths , so in case of Linq you have to implement something like that:

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);
        }
      }
    }
  }
}

Having Merge extension method, you can put

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM