How to insert newline in string literal?

前端 未结 12 774
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 09:07

In .NET I can provide both \\r or \\n string literals, but there is a way to insert something like \"new line\" special character like Enviro

12条回答
  •  抹茶落季
    2020-12-07 09:54

    One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine

    Usage

       " X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
       gives:
        X=1
        Y=2
        X+Y=3
    

    Code

        ///
        /// Use "string".FormatIt(...) instead of string.Format("string, ...)
        /// Use {nl} in text to insert Environment.NewLine 
        ///
        ///If format is null
        [StringFormatMethod("format")]
        public static string FormatIt(this string format, params object[] args)
        {
            if (format == null) throw new ArgumentNullException("format");
    
            return string.Format(format.Replace("{nl}", Environment.NewLine), args);
        }
    

    Note

    1. If you want ReSharper to highlight your parameters, add attribute to the method above

      [StringFormatMethod("format")]

    2. This implementation is obviously less efficient than just String.Format

    3. Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#

提交回复
热议问题