Why to use StringBuffer in Java instead of the string concatenation operator

It’s better to use StringBuilder (it’s an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here’s what happens: When you use + with two strings, it compiles code like this: String third = first + second; To something like this: StringBuilder builder = new StringBuilder( first ); … Read more

Efficiently repeat a character/string n times in Scala

For strings you can just write “abc” * 3, which works via StringOps and uses a StringBuffer behind the scenes. For characters I think your solution is pretty reasonable, although char.toString * n is arguably clearer. Do you have any reason to suspect the List.fill version isn’t efficient enough for your needs? You could write … Read more

How to construct a std::string from a std::vector?

C++03 std::string s; for (std::vector<std::string>::const_iterator i = v.begin(); i != v.end(); ++i) s += *i; return s; C++11 (the MSVC 2010 subset) std::string s; std::for_each(v.begin(), v.end(), [&](const std::string &piece){ s += piece; }); return s; C++11 std::string s; for (const auto &piece : v) s += piece; return s; Don’t use std::accumulate for string concatenation, … Read more

Is python += string concatenation bad practice?

Is it bad practice? It’s reasonable to assume that it isn’t bad practice for this example because: The author doesn’t give any reason. Maybe it’s just disliked by him/her. Python documentation doesn’t mention it’s bad practice (from what I’ve seen). foo += ‘ooo’ is just as readable (according to me) and is approximately 100 times … Read more

Create a comma-separated strings in C#

If you put all your values in an array, at least you can use string.Join. string[] myValues = new string[] { … }; string csvString = string.Join(“,”, myValues); You can also use the overload of string.Join that takes params string as the second parameter like this: string csvString = string.Join(“,”, value1, value2, value3, …);

String concatenation without ‘+’ operator

From the docs: Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, “hello” ‘world’ is equivalent to “helloworld”. Statement 3 doesn’t work because: The ‘+’ operator must be used to concatenate string expressions at run time. Notice that the title … Read more