Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation VS string format

Tags:

delphi

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

For instance, what is the better to use:

 s:=v1+' '+v2 

or

s:=format('%S %S',[v1,v2])
like image 349
Illya Pavlov Avatar asked Sep 09 '09 15:09

Illya Pavlov


People also ask

What are the benefits of using the format method instead of string concatenation?

The main advantages of using format(…) are that the string can be a bit easier to produce and read as in particular in the second example, and that we don't have to explicitly convert all non-string variables to strings with str(…).

Should I use string format?

tl;dr. Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

What is a string formatting?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text. custom_string = "String formatting" print(f"{custom_string} is a powerful technique") Powered by Datacamp Workspace. String formatting is a powerful technique.


1 Answers

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.

like image 161
Mason Wheeler Avatar answered Sep 19 '22 17:09

Mason Wheeler