Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings doesn't work as expected [closed]

I know it is a common issue, but looking for references and other material I don't find a clear answer to this question.

Consider the following code:

#include <string>  // ... // in a method std::string a = "Hello "; std::string b = "World"; std::string c = a + b; 

The compiler tells me it cannot find an overloaded operator for char[dim].

Does it mean that in the string there is not a + operator?

But in several examples there is a situation like this one. If this is not the correct way to concat more strings, what is the best way?

like image 464
Andry Avatar asked Nov 29 '10 14:11

Andry


People also ask

Is concatenating two strings a constant time operation?

Yes, in your case*1 string concatenation requires all characters to be copied, this is a O(N+M) operation (where N and M are the sizes of the input strings). M appends of the same word will trend to O(M^2) time therefor.

How do you concatenate a long string?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

Can you use += for string concatenation?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .

Why should you be careful about string concatenation (+) operator in loops?

If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.


1 Answers

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world"; 

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world"; 
like image 169
Konrad Rudolph Avatar answered Oct 01 '22 23:10

Konrad Rudolph