String concatenation VS string format

后端 未结 4 2336
無奈伤痛
無奈伤痛 2021-02-19 05:23

What is the best approach, simple string concatenation or string.format?

For instance, what is the better to use:

 s:=v1+\' \'+v2 
         


        
相关标签:
4条回答
  • 2021-02-19 05:55

    Here's a third option:

    s:=Concat(V1,V2);
    
    0 讨论(0)
  • 2021-02-19 05:57

    Format works with internationalization, making it possible to localize your app. Concatenation does not. Hence, I favor format for any display which may have to be produced in a culture-dependent manner.

    Update: The reason format works for internationalization is that not all languages express everything in the same order. A contrived example would be:

    resourcestring
        sentence = ' is ';
    
    var
        subject = 'Craig';
        adjective = 'helpful';
    begin
       WriteLn(subject + sentence + adjective + '!');
    

    This works, and I can customize with a resourcestring, but in Spanish I would write, "¡Qué servicial es Craig!" The resourcestring doesn't help me. Instead I should write:

    resourcestring
        sentence = '%S is %S!'; // ES: '¡Qué %1:S es %0:S!'
    
    0 讨论(0)
  • 2021-02-19 06:11

    I use:

    s := v1 + ' ' + v2;
    

    It's clearest and easiest to understand.

    That is the most important thing.

    You may find a construct that is marginally more efficient, e.g. using TStringBuilder in Delphi 2009. If efficiency is of utmost importance, then do what's necessary in the two or three most critical lines. Everywhere else, use code and constructs that are clear and easy to understand.

    0 讨论(0)
  • 2021-02-19 06:16

    Depends on your criteria for "best". If all you're doing is concatenating two strings, I'd go with the + operator. It's obvious what you're trying to do and easy to read, and it's a little bit faster because it doesn't have to use variants. (Have you looked at what format actually does under the hood? it's kinda scary!)

    The major advantage of format is that it lets you make a single string and store it somewhere, such as in a text file or a resourcestring, and gather other parameters later. This makes it useful for more complex tasks. But if all you need to do is stick two strings together, it's kinda overkill IMO.

    0 讨论(0)
提交回复
热议问题