Multiline string literal in C#

后端 未结 13 1467
梦谈多话
梦谈多话 2020-11-22 11:15

Is there an easy way to create a multiline string literal in C#?

Here\'s what I have now:

string query = \"SELECT foo, bar\"
+ \" FROM table\"
+ \" W         


        
相关标签:
13条回答
  • 2020-11-22 11:33

    As a side-note, with C# 6.0 you can now combine interpolated strings with the verbatim string literal:

    string camlCondition = $@"
    <Where>
        <Contains>
            <FieldRef Name='Resource'/>
            <Value Type='Text'>{(string)parameter}</Value>
        </Contains>
    </Where>";
    
    0 讨论(0)
  • 2020-11-22 11:35

    Yes, you can split a string out onto multiple lines without introducing newlines into the actual string, but it aint pretty:

    string s = $@"This string{
    string.Empty} contains no newlines{
    string.Empty} even though it is spread onto{
    string.Empty} multiple lines.";
    

    The trick is to introduce code that evaluates to empty, and that code may contain newlines without affecting the output. I adapted this approach from this answer to a similar question.

    There is apparently some confusion as to what the question is, but there are two hints that what we want here is a string literal not containing any newline characters, whose definition spans multiple lines. (in the comments he says so, and "here's what I have" shows code that does not create a string with newlines in it)

    This unit test shows the intent:

        [TestMethod]
        public void StringLiteralDoesNotContainSpaces()
        {
            string query = "hi"
                         + "there";
            Assert.AreEqual("hithere", query);
        }
    

    Change the above definition of query so that it is one string literal, instead of the concatenation of two string literals which may or may not be optimized into one by the compiler.

    The C++ approach would be to end each line with a backslash, causing the newline character to be escaped and not appear in the output. Unfortunately, there is still then the issue that each line after the first must be left aligned in order to not add additional whitespace to the result.

    There is only one option that does not rely on compiler optimizations that might not happen, which is to put your definition on one line. If you want to rely on compiler optimizations, the + you already have is great; you don't have to left-align the string, you don't get newlines in the result, and it's just one operation, no function calls, to expect optimization on.

    0 讨论(0)
  • 2020-11-22 11:40

    You can use this two methods :

        private static String ReverseString(String str)
        {
            int word_length = 0;
            String result = "";
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ' ')
                {
                    result = " " + result;
                    word_length = 0;
                }
                else
                {
                    result = result.Insert(word_length, str[i].ToString());
                    word_length++;
                }
            }
            return result;
        }
    //NASSIM LOUCHANI
        public static string SplitLineToMultiline(string input, int rowLength)
        {
            StringBuilder result = new StringBuilder();
            StringBuilder line = new StringBuilder();
    
            Stack<string> stack = new Stack<string>(ReverseString(input).Split(' '));
    
            while (stack.Count > 0)
            {
                var word = stack.Pop();
                if (word.Length > rowLength)
                {
                    string head = word.Substring(0, rowLength);
                    string tail = word.Substring(rowLength);
    
                    word = head;
                    stack.Push(tail);
                }
    
                if (line.Length + word.Length > rowLength)
                {
                    result.AppendLine(line.ToString());
                    line.Clear();
                }
    
                line.Append(word + " ");
            }
    
            result.Append(line);
            return result.ToString();
        }
    

    In the SplitLineToMultiline() , you need to define the string you want to use and the row length , it's very simple . Thank you .

    0 讨论(0)
  • 2020-11-22 11:43

    If you don't want spaces/newlines, string addition seems to work:

    var myString = String.Format(
      "hello " + 
      "world" +
      " i am {0}" +
      " and I like {1}.",
      animalType,
      animalPreferenceType
    );
    // hello world i am a pony and I like other ponies.
    

    You can run the above here if you like.

    0 讨论(0)
  • 2020-11-22 11:47

    Why do people keep confusing strings with string literals? The accepted answer is a great answer to a different question; not to this one.

    I know this is an old topic, but I came here with possibly the same question as the OP, and it is frustrating to see how people keep misreading it. Or maybe I am misreading it, I don't know.

    Roughly speaking, a string is a region of computer memory that, during the execution of a program, contains a sequence of bytes that can be mapped to text characters. A string literal, on the other hand, is a piece of source code, not yet compiled, that represents the value used to initialize a string later on, during the execution of the program in which it appears.

    In C#, the statement...

     string query = "SELECT foo, bar"
     + " FROM table"
     + " WHERE id = 42";
    

    ... does not produce a three-line string but a one liner; the concatenation of three strings (each initialized from a different literal) none of which contains a new-line modifier.

    What the OP seems to be asking -at least what I would be asking with those words- is not how to introduce, in the compiled string, line breaks that mimick those found in the source code, but how to break up for clarity a long, single line of text in the source code without introducing breaks in the compiled string. And without requiring an extended execution time, spent joining the multiple substrings coming from the source code. Like the trailing backslashes within a multiline string literal in javascript or C++.

    Suggesting the use of verbatim strings, nevermind StringBuilders, String.Joins or even nested functions with string reversals and what not, makes me think that people are not really understanding the question. Or maybe I do not understand it.

    As far as I know, C# does not (at least in the paleolithic version I am still using, from the previous decade) have a feature to cleanly produce multiline string literals that can be resolved during compilation rather than execution.

    Maybe current versions do support it, but I thought I'd share the difference I perceive between strings and string literals.

    UPDATE:

    (From MeowCat2012's comment) You can. The "+" approach by OP is the best. According to spec the optimization is guaranteed: http://stackoverflow.com/a/288802/9399618

    0 讨论(0)
  • 2020-11-22 11:48

    It's called a verbatim string literal in C#, and it's just a matter of putting @ before the literal. Not only does this allow multiple lines, but it also turns off escaping. So for example you can do:

    string query = @"SELECT foo, bar
    FROM table
    WHERE name = 'a\b'";
    

    This includes the line breaks (using whatever line break your source has them as) into the string, however. For SQL, that's not only harmless but probably improves the readability anywhere you see the string - but in other places it may not be required, in which case you'd either need to not use a multi-line verbatim string literal to start with, or remove them from the resulting string.

    The only bit of escaping is that if you want a double quote, you have to add an extra double quote symbol:

    string quote = @"Jon said, ""This will work,"" - and it did!";
    
    0 讨论(0)
提交回复
热议问题