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])
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(…).
tl;dr. Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With