String - append char

Brad Anderson eco at gnuk.net
Wed Oct 9 13:54:36 PDT 2013


On Wednesday, 9 October 2013 at 20:47:04 UTC, Matesax wrote:
> Hi,
> I need to append chars into string in foreach statement.
>
> void main(string[] args)
> {
> 	string
>
> 		result = "",
> 		source = chomp(readText(args[1]));
>
> 	foreach(int index, char letter; source)
> 		result += letter; //14
>
> 	writeln(result);
> }
>
> But it returning:
>
> main.d:14: Error: 'result' is not a scalar, it is a string
> main.d:14: Error: incompatible types for ((result) += 
> (letter)): 'string' and 'char'
>
> I try an pointer, but it damaged a string...
> Thank you for help.

Concatenation uses the ~ operator so change your foreach body to:

result ~= letter;

Strings in D are immutable so you could have just assigned them 
too (result = source) with almost the same result (the memory 
locations would be the same but that isn't a problem because of 
the aforementioned immutability).

In the future I recommend posting general questions about D to 
the D.learn NG/forum where more people will see them.  This forum 
is for GDC specific discussion.


More information about the D.gnu mailing list