Concatenate Literal with Optional String

Concatenate literal with Optional String

You can use the map method of Optional:

let username = name.map { "@" + $0 }

If name is nil then the closure is not executed and the result is nil. Otherwise the closure is evaluated with $0 set to the unwrapped name.

Concatenate two string literals

const string message = "Hello" + ",world" + exclam;

The + operator has left-to-right associativity, so the equivalent parenthesized expression is:

const string message = (("Hello" + ",world") + exclam);

As you can see, the two string literals "Hello" and ",world" are "added" first, hence the error.

One of the first two strings being concatenated must be a std::string object:

const string message = string("Hello") + ",world" + exclam;

Alternatively, you can force the second + to be evaluated first by parenthesizing that part of the expression:

const string message = "Hello" + (",world" + exclam);

It makes sense that your first example (hello + ",world" + "!") works because the std::string (hello) is one of the arguments to the leftmost +. That + is evaluated, the result is a std::string object with the concatenated string, and that resulting std::string is then concatenated with the "!".


As for why you can't concatenate two string literals using +, it is because a string literal is just an array of characters (a const char [N] where N is the length of the string plus one, for the null terminator). When you use an array in most contexts, it is converted into a pointer to its initial element.

So, when you try to do "Hello" + ",world", what you're really trying to do is add two const char*s together, which isn't possible (what would it mean to add two pointers together?) and if it was it wouldn't do what you wanted it to do.


Note that you can concatenate string literals by placing them next to each other; for example, the following two are equivalent:

"Hello" ",world"
"Hello,world"

This is useful if you have a long string literal that you want to break up onto multiple lines. They have to be string literals, though: this won't work with const char* pointers or const char[N] arrays.

How to concatenate two string in Dart?

There are 3 ways to concatenate strings

String a = 'a';
String b = 'b';

var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';

Usually string interpolation is preferred over the + operator.

There is also StringBuffer for more complex and performant string building.

JavaScript String concatenation behavior with null or undefined values

What is the prettiest way to concatenate String with potential null or undefined object without falling into this problem [...]?

There are several ways, and you partly mentioned them yourself. To make it short, the only clean way I can think of is a function:

const Strings = {};
Strings.orEmpty = function( entity ) {
return entity || "";
};

// usage
const message = "This is a " + Strings.orEmpty( test );

Of course, you can (and should) change the actual implementation to suit your needs. And this is already why I think this method is superior: it introduced encapsulation.

Really, you only have to ask what the "prettiest" way is, if you don't have encapsulation. You ask yourself this question because you already know that you are going to get yourself into a place where you cannot change the implementation anymore, so you want it to be perfect right away. But that's the thing: requirements, views and even envrionments change. They evolve. So why not allow yourself to change the implementation with as little as adapting one line and perhaps one or two tests?

You could call this cheating, because it doesn't really answer how to implement the actual logic. But that's my point: it doesn't matter. Well, maybe a little. But really, there is no need to worry because of how simple it would be to change. And since it's not inlined, it also looks a lot prettier – whether or not you implement it this way or in a more sophisticated way.

If, throughout your code, you keep repeating the || inline, you run into two problems:

  • You duplicate code.
  • And because you duplicate code, you make it hard to maintain and change in the future.

And these are two points commonly known to be anti-patterns when it comes to high-quality software development.

Some people will say that this is too much overhead; they will talk about performance. It's non-sense. For one, this barely adds overhead. If this is what you are worried about, you chose the wrong language. Even jQuery uses functions. People need to get over micro-optimization.

The other thing is: you can use a code "compiler" = minifier. Good tools in this area will try to detect which statements to inline during the compilation step. This way, you keep your code clean and maintainable and can still get that last drop of performance if you still believe in it or really do have an environment where this matters.

Lastly, have some faith in browsers. They will optimize code and they do a pretty darn good job at it these days.

How can I concatenate regex literals in JavaScript?

Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:

var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
segment_part + /* that was defined just now */
"another segment");

If you have two regular expression literals, you can in fact concatenate them using this technique:

var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(expression_one.source + expression_two.source, flags);
// regex3 is now /foobar/gy

It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.

How do I concatenate multiple C++ strings on one line?

#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();

Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm

Most efficient way to concatenate Strings

String.concat is faster than the + operator if you are concatenating two strings... Although this can be fixed at any time and may even have been fixed in java 8 as far as I know.

The thing you missed in the first post you referenced is that the author is concatenating exactly two strings, and the fast methods are the ones where the size of the new character array is calculated in advance as str1.length() + str2.length(), so the underlying character array only needs to be allocated once.

Using StringBuilder() without specifying the final size, which is also how + works internally, will often need to do more allocations and copying of the underlying array.

If you need to concatenate a bunch of strings together, then you should use a StringBuilder. If it's practical, then precompute the final size so that the underlying array only needs to be allocated once.

How do I concatenate strings in Swift?

You can concatenate strings a number of ways:

let a = "Hello"
let b = "World"

let first = a + ", " + b
let second = "\(a), \(b)"

You could also do:

var c = "Hello"
c += ", World"

I'm sure there are more ways too.

Bit of description

let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

Note

In reality let and var are very different from NSString and NSMutableString but it helps the analogy.

How to efficiently concatenate strings in go

New Way:

From Go 1.10 there is a strings.Builder type, please take a look at this answer for more detail.

Old Way:

Use the bytes package. It has a Buffer type which implements io.Writer.

package main

import (
"bytes"
"fmt"
)

func main() {
var buffer bytes.Buffer

for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}

fmt.Println(buffer.String())
}

This does it in O(n) time.



Related Topics



Leave a reply



Submit