c# string formatting

前端 未结 13 1517
离开以前
离开以前 2020-12-25 14:12

I m curious why would i use string formatting while i can use concatenation such as

Console.WriteLine(\"Hello {0} !\", name);

Console.WriteLine(\"Hello \"+          


        
相关标签:
13条回答
  • 2020-12-25 14:26

    You are using a trivial example where there is not much of a difference. However, if you have a long string with many parameters it is much nicer to be able to use a format string instead of many, many + signs and line breaks.

    It also allows you to format numerical data as you wish, i.e., currency, dates, etc.

    0 讨论(0)
  • 2020-12-25 14:34

    You picked too simple of an example.

    String formatting:

    • allows you to use the same variable multiple times: ("{0} + {0} = {1}", x, 2*x)
    • automatically calls ToString on its arguments: ("{0}: {1}", someKeyObj, someValueObj)
    • allows you to specify formatting: ("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate)
    • allows you to set padding easily: (">{0,3}<", "hi"); // ">hi <"
    0 讨论(0)
  • 2020-12-25 14:34

    String formatting allows you to keep the format string separate, and use it where it's needed properly without having to worry about concatenation.

    string greeting = "Hello {0}!";
    Console.WriteLine(greeting, name);
    

    As for why you would use it in the exact example you gave... force of habit, really.

    0 讨论(0)
  • 2020-12-25 14:34

    I think a good example is about i18n and l10n

    If you have to change a string between different languages, this: "bla "+variable+"bla bla.." Will give problems to a program used to create sobstitution for your strings if you use a different language

    while in this way: "bla {0} blabla" is easily convertible (you will get {0} as part of the string)

    0 讨论(0)
  • 2020-12-25 14:35

    Formatting is usually preferred for most of the reasons explained by other members here. There are couple more reasons I want to throw in from my short programming experience:

    • Formatting will help in generating Culture aware strings.
    • Formatting is more performant than concatenation. Remember, every concatenation operation will involve creation of temporary intermediate strings. If you have a bunch of strings you need to concatenate, you are better off using String.Join or StringBuilder.
    0 讨论(0)
  • 2020-12-25 14:35

    In addition to reasons like Ignacio's, many (including me) find String.Format-based code much easier to read and alter.

    string x = String.Format(
      "This file was last modified on {0} at {1} by {2}, and was last backed up {3}."
      date, time, user, backupDate);
    

    vs.

    string x = "This file was last modified on " + date + " at "
    + time + " by " + user + " and was last backed up " + backupDate + ".";
    
    0 讨论(0)
提交回复
热议问题