C #: How to add text to each line of a line?

How would the "MagicFunction" implementation be implemented to make the next (nunit) test pass?

public MagicFunction_Should_Prepend_Given_String_To_Each_Line()
{
    var str = @"line1
line2
line3";

    var result = MagicFunction(str, "-- ");

    var expected = @"-- line1
-- line2
-- line3";

    Assert.AreEqual(expected, result);
}

      

+2


source to share


8 answers


Thanks everyone for your answers. I have implemented MagicFunction as an extension method. It uses Thomas Levesque's answer, but is improved to handle all major environments AND assumes that you want the output line to use the same newline terminator of the input line.

I approved of Thomas Levesque's answer (over Spencer Ruport, Fredrik Morck, Lazar and J. Dunkerly) because it was the best result. I will post the results of the work on my blog and link back here later for those interested.



(Obviously the function name "MagicFunctionIO" needs to be changed. I went with "PrependEachLineWith")

public static string MagicFunctionIO(this string self, string prefix)
{
  string terminator = self.GetLineTerminator();
  using (StringWriter writer = new StringWriter())
  {
    using (StringReader reader = new StringReader(self))
    {
      bool first = true;
      string line;
      while ((line = reader.ReadLine()) != null)
      {
        if (!first)
          writer.Write(terminator);
        writer.Write(prefix + line);
        first = false;
      }
      return writer.ToString();
    }
  }
}

public static string GetLineTerminator(this string self)
{
  if (self.Contains("\r\n")) // windows
    return "\r\n";
  else if (self.Contains("\n")) // unix
    return "\n";
  else if (self.Contains("\r")) // mac
    return "\r";
  else // default, unknown env or no line terminators
    return Environment.NewLine;
}

      

0


source


string MagicFunction(string str, string prepend)
{
   str = str.Replace("\n", "\n" + prepend);
   str = prepend + str;
   return str;
}

      



EDIT:
As others have pointed out, newlines are different between environments. If you only plan to use this feature for files created in the same environment, then System.Environment will work fine. However, if you create a file in a Linux box and then drag it to a Windows box, you need to specify a different newline type. Since Linux uses \ n and Windows uses \ r \ n, this piece of code will work for both Windows and Linux files. If you're throwing a Mac into the mix (\ r), you'll have to come up with something more active.

+7


source


private static string MagicFunction(string str, string prefix)
{
    string[] lines = str.Split(new[] { '\n' });
    return string.Join("\n", lines.Select(s => prefix + s).ToArray());
}

      

+3


source


var result = "-- " + str.Replace(Environment.NewLine, Environment.NewLine + "-- ");

      

if you want it to handle Windows (\ r \ n) NewLines or Unix (\ n) then:

var result = "-- " + str.Replace("\n", "\n-- ");

      

There is no need to touch the \ r as it should be left where it was before. If you want to cross Unix and Windows, then:

var result = "-- " + str.Replace("\r","").Replace("\n", Enviornment.NewLine + "-- ");

      

This will do and return the result in local OS format

+1


source


You can do it like this:

public string MagicFunction2(string str, string prefix)
{
    bool first = true;
    using(StringWriter writer = new StringWriter())
    using(StringReader reader = new StringReader(str))
    {
        string line;
        while((line = reader.ReadLine()) != null)
        {
            if (!first)
                writer.WriteLine();
            writer.Write(prefix + line);
            first = false;
        }
        return writer.ToString();
    }
}

      

+1


source


What about:

string MagicFunction(string InputText) {
    public static Regex regex = new Regex(
          "(^|\\r\\n)",
        RegexOptions.IgnoreCase
        | RegexOptions.CultureInvariant
        | RegexOptions.IgnorePatternWhitespace
        | RegexOptions.Compiled
        );

    // This is the replacement string
    public static string regexReplace = 
          "$1-- ";

    // Replace the matched text in the InputText using the replacement pattern
    string result = regex.Replace(InputText,regexReplace);

    return result;
}

      

+1


source


You can split the line into Environment.NewLine and then prefix each of those lines and then attach them to Environment.NewLine.

string MagicFunction(string prefix, string orignalString)
{
    List<string> prefixed = new List<string>();
    foreach (string s in orignalString.Split(new[]{Environment.NewLine}, StringSplitOptions.None))
    {
        prefixed.Add(prefix + s);
    }

    return String.Join(Environment.NewLine, prefixed.ToArray());
}

      

0


source


How about this. It uses StringBuilder if you plan on adding many lines.

string MagicFunction(string input)
{
  StringBuilder sb = new StringBuilder();
  StringReader sr = new StringReader(input);
  string line = null;

  using(StringReader sr = new StringReader(input))
  {
    while((line = sr.ReadLine()) != null)
    {
      sb.Append(String.Concat("-- ", line, System.Environment.NewLine));
    }
  }
  return sb.ToString();
}

      

0


source







All Articles