Concatenation/joining strings together in a more readable way

Marcone marcone at email.com
Mon Dec 30 06:47:37 UTC 2019


On Wednesday, 25 December 2019 at 13:07:44 UTC, mipri wrote:
> On Wednesday, 25 December 2019 at 12:39:08 UTC, BoQsc wrote:
>> Are there any other ways to join two strings without Tilde ~
>> character?
>> I can't seems to find anything about Tilde character 
>> concatenation easily, nor the alternatives to it. Can someone
>> share some knowledge on this or at least point out useful
>> links/resources?
>
> Huh?
>
> For clarity I'm going to respond to some potential rewrites of
> your question.
>
>> I don't think "foo" ~ "bar" is very readable. Can I use a
>> different syntax?
>
> No. That's the syntax. Even if you customize it in your own
> code, by overloading addition or the like, you'll still come
> across it in other people's code. So I can only recommend that
> you find some way to make it readable for you. Maybe use a
> different or larger font? Maybe just get more familiar with it?
>
> I don't think the syntax is likely to change.
>
>> Where can I find documentation for the ~ operator?
>
> It's under 'expressions' in the spec:
>
> https://dlang.org/spec/expression.html#cat_expressions
>
>> Is ~ the best way to join strings together? Can I use
>> something else?
>
> You can use it to join arrays in general, including strings.
> Depending on your use case you might prefer joiner()
>
> https://dlang.org/phobos/std_algorithm_iteration.html#.joiner
>
> in usage like
>
>   assert(["many", "strings"].joiner("").array == "manystrings");
>
> Or Appender, for many mutating appends to the same array:
>
> https://dlang.org/phobos/std_array.html#Appender

Use Python format() style:

import std;
import std: Format = format;

// format()
string format(T...)(T text){
	string texto = text[0];
	foreach(count, i; text[1..$]){
		texto = texto.replaceFirst("{}", to!string(i));
		texto = texto.replace("{%s}".Format(to!string(count)), 
to!string(i));
	}
	return texto;
}

void main()
{
     string name = "Marcone";
     writeln("Helo {}".format(name)); // Helo Marcone
     writeln("Helo {0}".format(name)); // Helo Marcone
}


More information about the Digitalmars-d-learn mailing list